Using moment.js, I'm attempting to extract the offset from an ISO date string so I can use the offset later when formatting an epoch timestamp to ensure the conversion of the timestamp is in the same timezone.
Even though the offset in the string is -0400, the result is always 0;
var currentTime = "2015-03-18T16:10:00.001-0400";
var utcOffset = moment(currentTime).utcOffset(); // 0
I've attempted to use parseZone() as well without success. Is there a way to extract -0400 from the string so I can use it while formatting another time?
Thanks for the help!
KC
The correct way to extract the offset is indeed with parseZone
var currentTime = "2015-03-18T16:10:00.001-0400";
var utcOffset = moment.parseZone(currentTime).utcOffset();
This should result in -240, which means 240 minutes behind UTC, which is the same as the -0400 in the input string. If you wanted the string form, instead of utcOffset() you could use .format('Z') for "-04:00" or .format('ZZ') for "-0400".
The form you gave in the question just uses the computer's local time zone. So it is currently UTC+00:00 in your time zone (or wherever the code is running), that would explain why you would get a zero. You have to use parseZone to retain the offset of the input string.
Also - your use case is a bit worrying. Remember, an offset is not the same thing as a time zone. A time zone can change its offset at different points in time. Many time zones do this to accommodate daylight saving time. If you pick an offset off of one timestamp and apply it to another, you don't have any guarantees that the offset is correct for the new timestamp.
As an example, consider the US Eastern time zone, which just changed from UTC-05:00 to UTC-04:00 when daylight saving time took effect on March 8th, 2015. If you took a value like the one you provided, and applied it to a date of March 1st, you would be placing it into the Atlantic time zone instead of the Eastern time zone.
Related
I tried looking for an answer but could not find a particular answer which does with Timezone offset. Hence, posting the same really sorry if there are any answer present already.
I have a requirement in the project where I need to convert the time to UTC or GMT based on the time specified by the user and timezone offset value provided by the user. Basically, the user provides his local time and timezone offset value according to his local time. I need to convert that into UTC/GMT time.
I am using the Node.js and following is the data which is available in the Node.js Backend:
Time: 2020-11-05T15:00:00.000Z
Timezone offset value: +02:00
As the timezone offset value is +02:00 I need to subtract it from the time to convert it into the UTC format. so I can get the time as: 2020-11-05T13:00:00.000Z. I using the moment-js as well. Can someone please help me how can achieve this using the Node.js or using the Moment.js?
If the offset takes daylight saving time into account you should be able to do:
const the_date = '2020-11-05T15:00:00.000';
const offset = 2;
const utc_time = moment.utc(the_date).subtract(offset, 'hours');
It's not clear which way you are trying to convert. If you are converting from UTC to a fixed offset, you can use the utcOffset function, like this:
const m = moment.utc('2020-11-05T15:00:00.000Z').utcOffset('+02:00');
m.format(); //=> "2020-11-05T17:00:00+02:00"
Or - if you were trying to convert from +02:00, then you would include that offset in the input instead of the Z (Z means UTC). You would then just call the utc function, like this:
const m = moment('2020-11-05T15:00:00.000+02:00').utc();
m.format(); //=> "2020-11-05T13:00:00Z"
However you should be aware that an offset is not the same as a time zone. A time zone can have more than one offset, one of which will apply at a given point in time. Those offsets can change due to daylight saving time and for changes in standard time. Thus, asking a user to pick "his timezone offset value according to his local time" is problematic - as you may be applying that offset to the wrong point in time. See "Time Zone != Offset" in the timezone tag wiki for further details.
You should also understand Moment's project status, and possibly choose a different library.
After some more research and trying, I was able to convert it. Posting the answer in addition to Christians response (https://stackoverflow.com/a/64701083/7584240) so if anyone is looking for the answer they will have another option:
var moment = require('moment');
var time = "2020-11-05T15:00:00.000Z";
var timeoffset = "+02:00";
time = moment.utc(time).local().format('YYYY-MM-DDTHH:mm:SS.000');
time = moment(time, 'YYYY-MM-DDTHH:mm:ss.000').subtract(timeoffset).format('YYYY-MM-DDTHH:mm:ss.000') + 'Z';
I need to display on the screen some date values but I'm receiving them in a format that I don't know. Does anybody know what format is this and how to convert them?
For example, I'm getting this:
/Date(1427982649000-0400)/
In the database is stored as
2015-04-02 09:50:49.000
I really don't know where to start looking at.
It's a unix timestamp in milliseconds, followed by a timezone (shift in hours differing from UTC).
So, it's UTC -4 hours, 1427982649 seconds after the 1st January of 1970.
Nice little tool for checking unix timestamps : http://www.unixtimestamp.com/index.php (don't forget to convert your milliseconds to seconds before posting them there)
/edit: To add some additional information - the "timezone shift" seems to be following RFC822 (and/or probably some other RFCs), that -0400 can be explained by the syntax "+/-HHMM" specified there, so to be exact it means -04 hours, 00 minutes.
The actual time and date gets converted into the milliseconds, and it follows the Unix time January 1st, 1970.
Because it is the date when the time for the Unix computer started.
But you can convert the milliseconds into the actual time by using some loops or conversions according to that time.
Does anybody know what format is this and how to convert them?
It seems that "/Date(1427982649000-0400)/" is a time value in milliseconds followed by an offset as ±HHmm. To convert that to a Date, use the time value adjusted by the offset.
Assuming the offset uses the typical sign convention, then a positive offset needs to be subtracted and negative offset added to get the correct UTC value, then something like the following should suit:
var s = '/Date(1427982649000-0400)/';
// Get the number parts
var b = s.match(/\d+/g);
// Get the sign of the offset
var sign = /-/.test(s)? -1 : +1;
// Adjust the time value by the offset converted to milliseconds
// and use to create a Date
var ms = +b[0] + sign * (b[1].slice(0,2)*3.6e6 + b[1].slice(-2)*6e4);
console.log(new Date(ms).toISOString()); // 2015-04-02T17:50:49.000Z
In your example, "2015-04-02 09:50:49.000" does not have a timezone, so it represents a different moment in time for each timezone with a different offset. If that is the actual value stored in the database, then I guess the missing timezone is UTC-0800. It is much better to store the values using UTC and to include the offset, then the host timezone is irrelevant.
Things are complicated here because ECMAScript timezone offsets are the opposite sign to the normal convention, i.e. positive for west of Greenwich and negative for east. If that convention is applied, then "/Date(1427982649000-0400)/" converts to 2015-04-02T09:50:49.000Z, which may be what you're after.
If that is the case, just change the sign in the line:
var sign = /-/.test(s)? -1 : +1;
to
var sign = /-/.test(s)? +1 : -1;
I use the moment-timezone v.0.5.3-2016c library to calculate the UTC offset for a timezone:
var z = moment().tz("America/Los_Angeles");
z.utcOffset(); // -420 mins or -7 hours
// check if DST is shifted
z.isDSTShifted(); // false
But here https://en.wikipedia.org/wiki/List_of_tz_database_time_zones the UTC offset for the America/Los_Angeles is -8 hours.
Moment uses the tzdb v.2016c and the wikipedia article too.
Well, why there are two different results here? And which result is right?
P.S.: there is the same difference for America/Kentucky/Monticello and Europe/Tiraspol, as well.
Calling the moment creation function, moment() without any arguments returns the current moment in time. Since time zone offsets vary depending on what date and time they are attached to, your results will vary depending on when you call this function.
If you want to know whether or not the time is daylight saving time or not, use isDST. The isDSTShifted function is for dealing with invalid local times, not checking DST. It probably could have been named better.
The USA is currently in DST (Daylight Savings Time). Therefore, I'd use the UTC DST Offset column, which shows -07:00.
I'm looking for best practices regarding dates - where it's the date itself that's important rather than a particular time on that day.
An excellent start was this question:
Daylight saving time and time zone best practices
I'd like some guidance applying this for my situation. I have medications starting on a particular date, and ending on another. I then need to query medications which are active in a given date range.
I've tried setting start and end dates as midnight local time, then storing in UTC on the database. I could add timezone entries too.
I'm using moment.js on both client and server, and can use moment timezone if needed.
I'm wondering how to deal with the effect of DST on my times - which makes an hour difference in my locally-midnight UTC times between DST and non DST periods.
The problem I have is for example when some medications have end dates set during a DST period, and some which were set in a non-DST period. Then, their UTC times differ by an hour. When a query is made for a particular date range starting at local midnight, it's not accurate as there are two different representations of midnight. The query itself may treat midnight as one of two different times, depending on when in the year the query is made.
The end result is that a medication may appear to end a day later than it should, or start a day earlier.
A simple but wonky workaround would be to consistently set the start date as 1am in standard (non DST) time, and end dates as 11:59pm standard (non DST) time, and query at midnight.
Or, should I check the start and end dates of each query, and work out what the UTC offset would be for each date?
But I'd much prefer to know what best practice is in this situation. Thanks.
Both the JavaScript Date object and the moment object in moment.js are for representing a specific instant in time. In other words, a date and a time. They internally track time by counting the number of milliseconds that have elapsed since the Unix Epoch (Midnight, Jan 1st 1970 UTC) - ignoring leap seconds.
That means, fundamentally, they are not the best way to work with whole calendar dates. When you have only a date, and you use a date+time value to track it, then you are arbitrarily assigning a time of day to represent the entire day. Usually, this is midnight - but as you pointed out, that leads to problems with daylight saving time.
Consider that in some parts of the world (such as Brazil) the transition occurs right at midnight - that is, in the spring, the clocks jump from 11:59:59 to 01:00:00. If you specify midnight on that date, the browser will either jump forward or jump backward (depending on which browser you are using)!
And if you convert a local date-at-midnight to a different time zone (such as UTC), you could change the date itself! If you must use a date+time to store a date-only value, use noon instead of midnight. This will mitigate most (but not all) of the adjustment issues.
The better idea is to treat whole dates as whole dates. Don't assign them a time, and don't try to adjust them to UTC. Don't use a Date or a moment. Instead, store them either as an ISO-8601 formatted string like "2014-11-25", or if you need to do math on them, consider storing them as an integer number of whole days since some starting value. For example, using the same Jan 1st 1970 epoch date, we can represent November 11th 2014 as 16399 with the following JavaScript:
function dateToValue(year, month, day) {
return Date.UTC(year, month-1, day) / 86400000;
}
function valueToDate(value) {
var d = new Date(86400000 * value);
return { year : d.getUTCFullYear(),
month : d.getUTCMonth() + 1,
day : d.getUTCDate()
};
}
There are a few other things to keep in mind when working with whole dates:
When working with ranges of whole dates, humans tend to use fully-inclusive intervals. For example, Jan 1st to Jan 2nd would be two days. This is different from date+time (and time-only) ranges, in which humans tend to use half-open intervals. For example, 1:00 to 2:00 would be one hour.
Due to time zones, everyone's concept of "today" is different around the globe. We usually define "today" by our own local time zone. So normally:
var d = new Date();
var today = { year : d.getFullYear(),
month : d.getMonth() + 1,
day : d.getDate()
};
You usually don't want to shift this to UTC or another time zone, unless your business operates globally under that time zone. This is rare, but it does occur. (Example, StackOverflow uses UTC days for its calculations of badges and other achievements.)
I hope this gets you started. You asked a fairly broad question, so I tried to answer in way that would address the primary concerns. If you have something more specific, please update your question and I'll try to respond.
If you would like even more information on this subject, I encourage you to watch my Pluralsight course, Date and Time Fundamentals.
I am trying to get a countdown to end Monday # midnight PST. I thought I had it working a week ago but apparently not.
I am using date.js
var monday = Date.today().next().monday();
var UTCmonday = new Date(monday.getTime() + monday.getTimezoneOffset() * 60000);
var PSTmonday = new Date(UTCmonday.setHours(UTCmonday.getHours() + 9));
$('#defaultCountdown').countdown({until: UTCmonday});
I think the problem is in determining UTC time? Am I right? How do I work this out?
Assuming you Pacific Standard Time, then you need to remember that PST === UTC-8
Thus, your third line would be
var PSTmonday = new Date(UTCmonday.setHours(UTCmonday.getHours() - 8));
The problem with this is that this will fail if the UTC is any earlier than 8am, since you can't pass a negative number into setHours.
Since you're using Datejs, why not use its full capabilities for changing the timezone?
http://code.google.com/p/datejs/wiki/APIDocumentation#setTimezone
Getting the time strictly in PST doesn't make much sense, as for almost half of the year PST isn't observed in the Pacific time zone. PST (UTC-8) is observed in the winter, and PDT (UTC-7) is observed in the summer. You can't represent Pacific Time as just a fixed offset, and unless it happens to be your own local time zone, you can't easily determine the transition between them without a time zone database. See the timezone tag wiki.
Also, date.js has been abandoned. I can't recommend any solution that continues its use. Support for the setTimezone method that Dancrumb suggested is culture specific, and it still doesn't take daylight saving time into consideration.
Instead, I recommend trying moment.js. You can use the moment-timezone add-on to work with the America/Los_Angeles zone - which is a good exemplar of US Pacific time. Make sure your moment-timezone-data.js file includes at least this zone. Then you can do the following:
var m = moment().tz('America/Los_Angeles').day(7).startOf('day');
var s = m.toISOString(); // if you need a string output representing UTC
var dt = m.toDate(); // if you need an actual JavaScript Date object
Let's break that down a bit:
moment() gets you the current time
tz('America/Los_Angeles') adjusts the time to the timezone you are interested in.
day(7) advances the time to the next Monday.
startOf('day') snaps the time back to midnight.