I have an API call that receives a date string like 2016-2-12 //('YYY-MM-DD').
I am using moment-timezone, but not having any luck.
The end goal is to get the unix timestamp for midnight 2016-2-12 of the timezone of the applicable site (not the server)
I have tried a lot of combinations of something like:
moment.tz('2016-2-12', 'America/New York').utc();
But it seems to receive the input date as UTC (my server is set to UTC) then do the timezone conversion AFTER, giving me a date for the day before.
For reference I am generating a report for a date range. So if the input is:
&start=2016-4-12&stop=2016-4-15 //and the timezone is America/New York
I expect a start time of 2016-4-12T00:00:00 -04:00 but i keep ending up with dates from the day before.
I expect the function to be something like:
moment.tz('2016-2-12', 'YYYY-MM-DD', 'America/New York').startOf('day').utc();
As soon as i asked the question, after hours of screwing around, i got it.
moment.tz('2016-4-14', 'YYYY-MM-DD', 'America/New York').format();
is yielding 2016-04-14T00:00:00-04:00
Sorry to waste time here... I hope someone else finds this helpful...
moment.tz('2016-4-14', 'YYYY-MM-DD', 'America/New York').endOf('day').format();
is yielding 2016-04-14T23:59:59-04:00 as well and i can easily get unix timestamp using utc()
Related
I have a piece of code which finds the difference between two dates(in the format of yyyy-MM-dd hh:mm:ss) . This code is run in multiple servers across the globe. One of the two dates is the current time in that particular timezone where the code is being run(server time) and another is the time obtained from a database. if the difference between these two times is greater than 86400 seconds(1day), then it should print "invalid" else, it should print "valid".
Problem im facing with the code is when I run it on my local, its working fine, but when i deploy it onto a server in US, its taking GMT time into consideration and not local time.
Wherever the code is run, I want the difference between current time and time fetched from the database, and if its greater than 86400 seconds, i want to print invalid. How to achieve this in java?
PS: I tried with Date object, but its considering GMT only everywhere.
I would use GMT everywhere and only convert to the local times for display purposes.
To find the difference, convert both times to the same timezone (say GMT) and take the difference.
You can do it by the below example code.
Date date = new Date();
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("CET"));
Date date1 = dateformat.parse(formatter.format(date));
// Set the formatter to use a different timezone
formatter.setTimeZone(TimeZone.getTimeZone("IST"));
Date date2 = dateformat.parse(formatter.format(date));
// Prints the date in the IST timezone
// System.out.println(formatter.format(date));
Now compare date1 with date2
First, I concur with Peter Lawrey's answer up there. It is usually good practice to store all time in the database for a single zone, and render it with offset for the user based upon the user's locale.
To find the difference, use the method getTime() to get the time in milliseconds from the epoch for each date. The calculation for the difference of 1 day is then 86400 * 1000 milliseconds. Or, perhaps, store the time in milliseconds from epoch in the database, and use a DB procedure/function at the time of retrieval.
Hope this helps.
I'm working on an app where users can choose what time zone they are recording time in. But internally, I want to store the time as a unix timestamp.
Say I have a date '2016-01-01 1:00 pm'. If I store this date in CDT (America/Chicago), it is my understanding that the resulting unix time stamp should be different than had I stored the same date in MDT (America/Denver). However, I get the same unix time stamp for both dates, and I'm having trouble understanding why.
var chicagoDate = moment('2016-01-01 1:00 pm').tz('America/Chicago');
var denverDate = moment('2016-01-01 1:00 pm').tz('America/Denver');
chicagoDate.format();
// "2016-01-01T07:00:00-06:00"
denverDate.format();
// "2016-01-01T06:00:00-07:00"
So far this confirms that the 2 dates are distinct from one another as shown by their UTC representation obtained by using format(). But here is where I'm getting confused:
chicagoDate.unix();
// 1451653200
denverDate.unix();
// 1451653200
Shouldn't 2 distinct UTC dates result in 2 distinct unix timestamps?
In:
moment('2016-01-01 1:00 pm').tz('America/Chicago');
there is no parse format parameter, so moment.js looks to see if the format is one that it can parse without the format. It can't, so it falls back to the built–in parser as if you'd written:
moment(new Date('2016-01-01 1:00 pm')).tz('America/Chicago');
And puts warning in the console:
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions…
Safari at least parses it as an invalid date (timestamp), so you should include the parse format:
moment(new Date('2016-01-01 1:00 pm', 'YYYY-MM-DD h:mm a')).tz('America/Chicago');
Secondly, the string is parsed as local since there is no timezone associated with the timestamp. So both lines of code produce exactly the same time value (i.e. offset from the epoch) and the two Dates produced are effectively identical.
The call to tz sets the timezone to use for all subsequent operations, so the output shows different times because different offsets have been applied at the formatting stage. The actual Dates being formatted are still effectively identical.
If you want the string to be parsed as for another timezone, you need to either manually include it in the string at the parse stage (e.g. '-06:00' or whatever), or use a library like Luxon with an IANA location (e.g. 'America/Chicago').
in my ASP.net application, in the js, i got the date format as '2017-04-26T09:00:00Z'. What is this format? And when i return this to the view page, the date is changed to 26/04/2017 02:00 am. But the actual time is 09.00 am. Kindly help me why this is happening? My js code is
{
"data": "Date",
"render": function (data) {
return moment(data).format('MM/DD/YYYY H:m');
}
}
'Z' stands for Zulu time, which is also GMT and UTC.
moment is converting that timestamp (your variable data) to your local timezone which appears to be 7 hours behind GMT.
Based on W3scholls :
Date and time is separated with a capital T
UTC time is defined with a capital letter Z
And if you test this link you will be get the secret behind this.
The date you see in the JS is actually your the date Time with your timezone. On server side it will automatically get converted to the UTC timezone.
you must be at UTC + 7:00Hrs time zone right.
If you want to get the Date right just strip the Time part in JS,
moment(data).format('MM/DD/YYYY');
I'm using moment.js with timezones to create a datetime belonging to a specific timezone:
var datetime = moment.tz("2016-08-16 21:51:28","Europe/London");
Because this constructor is aware of DST (daylight saving time), moment.js will add +1 hour offset automatically. datetime.format() will show: 2016-08-16T21:51:28+01:00.
But it seems when printing the date, the offset ins't considered. E.g. datetime.format('DD.MM.YYYY - HH:mm:ss') will show: 16.08.2016 - 21:51:28 but I wan't it to show: 16.08.2016 - 22:51:28 (the time considering the DST-Offset of 1 hour). Does anyone know how to do this?
You are misinterpreting the output you're getting.
When you see +01:00 at the end of an ISO8601 timestamp, it doesn't mean that you need to add an hour. It means that timestamp given is in a local time zone that is one hour ahead of UTC at that point in time. Moment isn't adding an hour. It's simply reflecting the local time in London.
For the timestamps you provided, showing 22:51:28 would be an error. The local time in London is 21:51:28, and the equivalent UTC time is 20:51:28. You wouldn't find 22:51:28 until you went one time zone to the East, at UTC+2.
Now, if what you meant to do is convert from UTC to London time, then you need to create the input as UTC and then convert.
moment.utc("2016-08-16 21:51:28").tz("Europe/London")
Then you'd get 22:51:28 when formatting, which is the result you asked for, but this is a different point in time.
I have a problem in getting unix timestamp on only date(Without time) in node js. I tried with moment js
I have tried this,
moment.unix();// which gives,1446090606
If i use the same i php,
echo date("Y-m-d H:i:s", 1446090606);// echoes 2015-10-29 04:50:06
But actual time stamp of today's date is 1446073200
echo date("Y-m-d H:i:s", 1446073200);// echoes 2015-10-29 00:00:00
I even tried with Date() in javascript,
I referred this, this but no use.
EDIT
I even tried like this,
console.log(moment("2015-10-29 00:00:00").unix());// which gives 1446057000
echo date("Y-m-d H:i:s", 1446057000);// echoes 2015-10-28 19:30:00
It echoes yesterday's date
To summarize what i want is, timestamp of only date without time.
Thank you.
So first you need to ask yourself what you are looking for ultimately. It's really in your best interest to keep all your timestamps in standard UTC format and, if you are storing strings, use the ISO8601 standard. For fun: XKCD on ISO8601
It will make your life so much easier to pass around dates in only one format (UTC timezone / ISO8601 format if a string) until just before you display them to a user.
Only then should you format the date as a user would expect it to be formatted to represent the local time, and you should write a date formatter to ensure this conversion is always done consistently.
On the client side, convert the date to this standardized format the moment it is captured by the user and before it is sent to the server (effectively a reverse of the formatter described above).
All of your server date logic beyond that will typically be calculating time differences without needing to worry about timezone conversions. /rant
Now to discuss your question in a bit more detail and why you are facing issues.
According to moment.js docs:
By default, moment parses and displays in local time.
So when you do this:
moment.unix();
Know that this is relative to the local time. Also unix time is the number of seconds relative to one singular point in time, an epoch which happens to be January 1st, 1970 00:00:00 (when put into the UTC timezone).
To make this hit home. Use your PHP date function and input "0" as the unix timestamp. What do you get? It will depend on the default timezone set in your PHP environment.
For me, the output of the online PHP sandbox I used:
<?php echo date('Y-m-d H:i:s', 0); ?>
// 1969-12-31 16:00:00
Uh oh. What's going on here? That's before epoch time, and I definitely just put a big fat ZERO there.
So this is the importance of keeping your date formats consistent across the board. It will make your life a lot easier.
Here is what you need to do and why:
1. Get the local date's midnight. This is the first piece of information you need to capture in a moment variable because it represents what you are interested in. Once you have that, the rest is just understanding how to format that date how you want.
var lastLocalMidnight = moment().startOf('day')
var lastUTCMidnight = moment.utc().startOf('day')
For the sake of argument and your understanding, I have included another variable which captures and converts "now" into the UTC timezone before getting "midnight".
So what's the difference here? Read the moment.js docs on UTC further:
Any moment created with moment.utc() will be in UTC mode, and any moment created with moment() will not.
To switch from UTC to local time, you can use moment#utc or
moment#local.
moment.js variables have timezone information self-contained within them when you perform other operations on them. It is important to distinguish the difference between this and the standard PHP Date behavior which treats dates the same (unless you explicitly say otherwise).
The timezone being used in every case needs to be known or set. Not understanding these two behaviors completely is most likely the source of your confusion.
A "date is a date is a date". A moment in time, hence the library name "moment.js". It needs to be stated or set what timezone that date is in. There are different formats to capture this information, but just understand that "2015-10-29 04:50:06" doesn't tell you anything until you know the timezone. It's basically the same as how 12:00 doesn't tell you anything until you know AM or PM (assuming you are not using military time).
2. Now that you have a midnight representation (whichever you deem is the correct one for your purposes), you can convert that to a UNIX timestamp because it is relative to a timezone you know you are interested in and represents the exact moment you want.
console.log(lastLocalMidnight.format());
// e.g. - 2015-10-28T00:00:00-06:00
console.log(lastUTCMidnight.format());
// e.g. - 2015-10-29T00:00:00+00:00
console.log(lastLocalMidnight.unix());
// e.g. - 1446012000
console.log(lastUTCMidnight.unix());
// e.g. - 1446076800
$timezoneBeforeSet = date_default_timezone_get();
echo $timezoneBeforeSet."\n";
Notice how moment.js's format() function displays the UTC offset by default. So even printing in that way looks like the midnight you want, but you know it wouldn't end in 00:00:00 if you formatted it to be in UTC (or any timezone other than the one you requested the date in originally).
For the moment converted to UTC ahead of time, there is no offset. If you later formatted that one in your local timezone, it would not be at 00:00:00, and the output of moment.js format() would indicate a timezone offset based on the timezone you set (-06:00, for example).
3. On the PHP side of things, you have a default environmental timezone set, as we demonstrated by seeing what PHP thought of the unix timestamp "0". So, knowing a little more about what they represent now, let's take the unix timestamps we obtained from moment.js and try to format them with PHP's date.
// Timestamps obtained from moment.js
$unixTimestampLocalMidnight = 1446012000;
$unixTimestampUTCMidnight = 1446076800;
// Relative to untampered timezone set in your PHP environment
$phpLocalMidnightUnchangedTZ = date('Y-m-d H:i:s', $unixTimestampLocalMidnight);
echo $phpLocalMidnightUnchangedTZ."\n";
// 2015-10-27 23:00:00
$phpUTCMidnightUnchangedTZ = date('Y-m-d H:i:s', $unixTimestampUTCMidnight);
echo $phpUTCMidnightUnchangedTZ."\n";
// 2015-10-28 17:00:00
So yeah. Those are totally not what we were wanting, right? Actually they are. It's 23:00:00 somewhere and 17:00:00 somewhere when it's midnight somewhere else, right?
We need to be sure where PHP thinks we are right now. We could output that timezone information using Date, but we don't care to see it in our final output (understandable). So how do we find out, otherwise? Glad you asked:
$timezoneBeforeSet = date_default_timezone_get();
echo $timezoneBeforeSet."\n";
// US/Pacific
I'm in Colorado which is US/Mountain, so what's the deal? Well, this must mean the online PHP sandbox I was using is hosted over in California or something. Makes sense. Know where your code is running.
But don't get too caught up worrying about that. This is why we capture and convert to a consistent format upfront and worry about formatting only at which point we really need it. That way, if you did your conversion wrong, you only need to change it in one or two places at most.
For a complete reference to PHP timezones, click here.
4. If you have any control of your PHP environment, you should be setting the default timezone to UTC (one of the very first things you do in your project bootstrapping or in your PHP environmental config file).
// Explicitly set PHP default timezone to UTC
date_default_timezone_set('UTC');
$timezoneAfterSet = date_default_timezone_get();
echo $timezoneAfterSet."\n";
// UTC
$phpLocalMidnight = date('Y-m-d H:i:s', $unixTimestampLocalMidnight);
echo $phpLocalMidnight."\n";
// 2015-10-28 06:00:00
$phpUTCMidnight = date('Y-m-d H:i:s', $unixTimestampUTCMidnight);
echo $phpUTCMidnight."\n";
// 2015-10-29 00:00:00
So this makes sense. We are showing a time relative to UTC now. If I had originally captured a midnight in US/Mountain time, I would expect to see a time of day that corresponds to that over in Greenwich, England.
When you know a date is formatted with a timezone, think of reading that date-time in the place the timezone indicates. We know PHP is spitting out UTC stuff, so I can imagine I'm in Greenwich, England when I see the output.
If it's 06:00 in the morning and I am in Greenwich, it should be 6 hours earlier in Colorado (-6:00) <-- remember that useful timezone suffix moment.js outputs with .format()? The sun hasn't quite risen yet in Colorado because the sun rises in the East and sets in the West. So what time is 6 hours before 6AM? Midnight!
And of course the date we explicitly converted to UTC upfront comes back out looking like an actual midnight. Why? Because PHP is set to format dates in UTC. Also notice it's a day ahead. You should know enough now to explain that yourself =)
Make sense?
You have to create the date without the hour part first, something like this:
var moment = require("moment");
var unixTime = moment().startOf('day').unix(); //last midnight in local time
console.log("Your timestamp: " + unixTime + " And your date: " + day);
Now, let's see your examples.
Yo said that this unix timestamp 1446073200 but, you when you check here, you can see that this is the date that represents:
UTC: Wednesday 28th October 2015 11:00:00 PM
And also gives you another date with your local time, which in my case:
In your local time zone: Wednesday 28th October 2015 05:00:00 PM
So, my guess is that you are getting that unix timestamps in a place with timezone UTC + 1 and that's why you believe that this unix timestamp 1446073200 has no the hour part.
In my previous example you will get a unix timestamp in your local time, which in my case is: 1446098400, but you will probably want the UTC time, so you should change the code a little bit, like this:
var moment = require("moment");
var unixTime = moment.utc().startOf('day').unix(); //last midnight in UTC time
console.log("Your timestamp: " + unixTime + " And your date: " + day);
That will give you this unix timestamp: 1446076800which is the one you need. You can check it here.
UTC: Thursday 29th October 2015 12:00:00 AM
I simplified my code using #forgo answer.
This is how I do in pure Javascript:
var today = new Date()
today.setUTCHours(0, 0, 0, 0)
var today_timestamp = Math.floor(today.getTime() / 1000)
If you want to get the value for the current timezone, use setHours instead.