formatting a moment object gives me a different result to the one I expect to see
I tried removing UTC but still don't get the result i expect
moment.utc().startOf("day").subtract(schedule.pastDays, "days")
returns date object with:
_d: Wed Jul 17 2019 00:00:00 GMT+0000 (Etc Greenwich Standard Time) {}
but formatting it:
moment.utc().startOf("day").subtract(schedule.pastDays, "days").format()
returns:
"2019-07-16T22:00:00Z"
Where did the 2hrs go that kicked the date back to the previous day?
I expected to see:
"2019-07-17T00:00:00Z" as the date object would suggest.
So if I do not specify a timezone, moment presumes utc and so adjusts when I format(). This however works and keeps the formatted time local:
var tzDay = moment().utcOffset(moment().utcOffset(), true).local()
var newDay = tzDay.format('MMDDYYYY');
console.log(newDay)
//returns today's date without any utc adjustment
Related
I am using in my database for Date and Time information the following format "yyyyMMddHHmmssSSS"
20211119143315000 and UTC. This corresponds to 19th November 2021 14:33:15 and 0 milliseconds in GMT+0.
The timezone is always UTC in the database. If my localtime in GMT 1 that example will be displayed as 19th November 2021 15:33:15 local time.
I use a DateTimePicker in my dialog and succeeded to display the correct local time with the following configuration in the XML View:
<DateTimePicker id="dp_lastUsedDate" valueFormat ="yyyyMMddHHmmssSSS Z" value="{path:'mdlPRTData>mp_last_used_date'}"/>
My issue is the format of the model value after I pick a date in the dialog. After I pick a date, the format of the value in the model is changed:
My actual local time is GMT+1
Original model value: 20211119143315000
Displayed value: 19.11.2021 15:33:15
Picked value: 19.11.2021 16:33:15
new model value: 20211119163315000 +0100
what I would expect: 20211119153315000
I could not find a solution (without making an individual change and formatter functions) for this requirement.´
Any tipps?
Don't understand why the examples on moment-timezone page give me different result than what they say they should.
Running these statements give me date with my current local time for each instance:
var jun = moment("2014-06-01T12:00:00Z");
var dec = moment("2014-12-01T12:00:00Z");
jun.tz('America/Los_Angeles').format('ha z'); // 5am PDT **I get 7am**
dec.tz('America/Los_Angeles').format('ha z'); // 4am PST **I get 6am**
What am I missing?
Found the issue was due to missing time zone data. After loading time zone data I get the expected results, below; how to load time zone data
[http://momentjs.com/timezone/docs/#/data-loading/][1]
I am using Splunk 6.2.X along with Django bindings to create a Splunk app.
To get access to the earliest/latest dates from the timerange picker, am using the following in my JS.
mysearchbar.timerange.val()
Am getting back a map where the values are in epoch format:
Object {earliest_time: 1440122400, latest_time: 1440124200}
When I convert them using moment using the following, I get different datetime than expected:
> moment.unix('1440122400').utc().toString()
"Fri Aug 21 2015 02:00:00 GMT+0000"
However, the time does not correspond to the values that have been selected on the time range picker i.e. 08/20/2015 22:00:00.000
Am not sure what the difference is getting caused by? Am sure tht the timezone is not the factor as the time difference is erratically not equivalent to derive using simple timezone add/subtract.
I was wondering if this behaviour can be explained as to how to get the Splunk epoch datetime to UTC would be helpful.
I was able to get rid of the timezone issue by performing the following:
Setting the timezone of the Splunk engine to UTC in props.conf as follows:
TZ = GMT
Setting up the CentOS (the server hosting Splunk) to UTC
Hope this helps anyone else who stumbles upon similar issues.
Thanks.
I'm working on a script that will look up an event on a community Google Calendar (using Eastern Time Zone) and successfully convert it to the local user's timezone. Because it is a community Google Calendar, I cannot set the time to display as UTC, which would theoretically make this that much easier. Here is a step-by-step process that I am attempting to create:
Get the event time as it stands (Eastern time) from Google Calendar. This is done quite easily using the API and json format.
Get the Eastern timezone offset based on the event time using Google Maps API. Again, this is easily done.
Convert the Event time from Eastern to UTC, which I believe is done by adding the offset to the Event time.
Calculate the local timezone/UTC timezone difference based on the future date.
Return the local time for the event by adding step 4's result to the UTC event's time.
However, no matter what I do, it seems to not work the way I want it. Here is the code as it stands:
local function get_local_time(dateTime)
local xyear, xmonth, xday = string.match(dateTime, "(%d+)%-(%d+)%-(%d+)") -- Date format is displayed as yyyy-mm-dd
local xhour, xmin = string.match(dateTime, "%a(%d+):(%d+)") -- Time format is displayed as Thh:mm
local event_time = os.time({year = xyear, month = xmonth, day = xday, hour = xhour or 23, min = xmin or 59, sec = 0}) -- Gets epoch time for event time
async_ok, async = pcall (require, "async") -- Asynchronous lookup functions
if not json then json = require 'json' end
tzpage = "https://maps.googleapis.com/maps/api/timezone/json?location=28.4158,-81.2989×tamp=" .. event_time .. "&key=" .. key -- Gets offset data for Eastern Time Zone
if async_ok then
tzrpage = async.request(tzpage, "HTTPS")
end
retval, page, status, headers, full_status = tzrpage:join()
tzrpage = nil
if status == 200 then
tzopage = json.decode(page)
end
local eastern_offset = tzopage.rawOffset+tzopage.dstOffset -- Adds the offset information together (includes Daylight Savings)
local utc_event_time = event_time+eastern_offset -- Sets UTC's time for the event
local utctime, localtime = os.date("!*t", utc_event_time), os.date("*t", utc_event_time) -- Sets table data for events based on UTC's time of the event
localtime.isdst = false
local localoffset = os.difftime(os.time(utctime), os.time(localtime)) -- Sets the time difference between UTC and local time at the time of the event UTC
return os.date("%A, %B %d %Y at %I:%M%p", (utc_event_time-localoffset)) -- Should return local time of the event
end
But when I do something like the following:
print(get_local_time("2015-10-31T01:15:00"))
it returns
Friday, October 30 2015 at 02:15PM
when it should be returning
Friday, October 30 2015 at 10:15PM
as I'm Pacific time.
If I change
return os.date("%A, %B %d %Y at %I:%M%p", (utc_event_time-localoffset))
to
return os.date("%A, %B %d %Y at %I:%M%p", (utc_event_time+localoffset))
I get
Saturday, October 31 2015 at 04:15AM
Which again, is incorrect.
Where am I going wrong with this script? As a side note, the async is a client dependency, but it's essentially http.request.
Convert the Event time from Eastern to UTC, which I believe is done by adding the offset to the Event time.
Subtracting.
The offset shown in a timestamp is a signed number. It's already been "added" to UTC to generate the local time, so the inverse operation would be to subtract it. With -0400 being negative, you'd need to subtract negative 4 hours to convert back to UTC.
I'm using the following functions:
# The epoch used in the datetime API.
EPOCH = datetime.datetime.fromtimestamp(0)
def timedelta_to_seconds(delta):
seconds = (delta.microseconds * 1e6) + delta.seconds + (delta.days * 86400)
seconds = abs(seconds)
return seconds
def datetime_to_timestamp(date, epoch=EPOCH):
# Ensure we deal with `datetime`s.
date = datetime.datetime.fromordinal(date.toordinal())
epoch = datetime.datetime.fromordinal(epoch.toordinal())
timedelta = date - epoch
timestamp = timedelta_to_seconds(timedelta)
return timestamp
def timestamp_to_datetime(timestamp, epoch=EPOCH):
# Ensure we deal with a `datetime`.
epoch = datetime.datetime.fromordinal(epoch.toordinal())
epoch_difference = timedelta_to_seconds(epoch - EPOCH)
adjusted_timestamp = timestamp - epoch_difference
date = datetime.datetime.fromtimestamp(adjusted_timestamp)
return date
And using them with the passed code:
twenty = datetime.datetime(2010, 4, 4)
print(twenty)
print(datetime_to_timestamp(twenty))
print(timestamp_to_datetime(datetime_to_timestamp(twenty)))
And getting the following results:
2010-04-04 00:00:00
1270339200.0
2010-04-04 01:00:00
For some reason, I'm getting an additional hour added in the last call, despite my code having, as far as I can see, no flaws.
Where is this additional hour coming from?
# Ensure we deal with `datetime`s.
date = datetime.datetime.fromordinal(date.toordinal())
(That's chopping off the time-of-day completely, as ‘ordinal’ is only a day number. Is that what you meant to do? I suspect not.)
Anyway, as Michael said, datetime.fromtimestamp gives you a naïve datetime corresponding to what local time for that POSIX (UTC) timestamp would be for you. So when you call —
date = datetime.datetime.fromtimestamp(adjusted_timestamp)
you're getting the local time for the POSIX timestamp representing 2010-04-04T00:00:00, which of course in BST is an hour ahead. This doesn't happen in the return direction because your epoch is in January, when BST is not in force. (However your EPOCH would also be completely off if you weren't in the UK.)
You should replace both your uses of datetime.fromtimestamp with datetime.utcfromtimestamp.
It's sad that datetime continues the awful time tradition of keeping times in local time. Calling them ‘naïve’ and taking away the DST flag just makes them even worse. Personally I can't stand to use datetime, preferring integer UTC timestamps for everything (converting to local timezones for formatting only).
Judging by your profile, you're in the UK. That means you're currently running on UTC+1 due to DST.
If I take your timestamp and run it through datetime.fromtimestamp on Python 2.6 (I know you use Python 3, but this is what I have), that shows me that it believes it refers to 2010-04-04 02:00:00 - and I'm in CEST, so that's UTC+2.
Running datetime.fromtimestamp(0), I get that the epoch is 1970-01-01 01:00:00. This then shows me that it is correctly adding only a single hour (since January 1st is outside of DST, and the epoch is midnight UTC on that date, it would be 01:00 here).
In other words, your problem is that you're sending in a time which has DST applied, but datetime_to_timestamp treats it as if DST didn't exist. timestamp_to_datetime, however, applies the DST.
Unfortunately, I don't know enough Python to know how you would solve this, but this should at least give you something to go on.