Error in date formatting JS - javascript

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');

Related

UTC displaying wrong times using moment.js [duplicate]

This question already has an answer here:
Why moment.js treats dash differently from slash?
(1 answer)
Closed last month.
I am trying to save a date and time for different time zones. I have changed my time zone in my chrome dev tools for testing purposes as follows
So for testing, I am trying to save a date time for London as '2023/04/21 23:55' when I save this datetimeoffset into my DB it gets stored as '2023-01-30T23:55:00+02:00'
but now when I try to read the format the date is as follows
var test = Moment(date); //'2023-01-30T23:55:00+02:00'
test = test.utc(true);
var format = "yyyy/MM/DD HH:mm";
return test.format(format);
it returns the date 2023/01/30 21:55. Why is it removing the 2 hours?
The issue is that your datetimeoffset has a timezone associated with it (+02:00). The 2023-01-30T23:55 part of your timestamp is not UTC time, it is local time, and the +02:00 signifies the offset of that timezone.
I'm not sure how you're saving that time in the first place, you probably forgot to specify the timezone as UTC. For example, if the date was created with Moment('2023-01-30T23:55:00'), then it that time will be intepreted as 23:55:00 on 2023-01-30 in the system's timezone, not UTC. To fix this, you need to use the Moment.utc('2023-01-30T23:55:00').

How to display Datetime considering offset using MomentJS with Timezones

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.

MomentJS Parse Midnight Local From Date String

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()

Get unix timestamp of only date in node js

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.

How do you account for time-zone offset when retriving an "All Day" event from Google Calendar API?

I have an Ajax call to retrieve information from a public Google Calendar:
$.ajax({
url: "https://www.google.com/calendar/feeds/{CalID}/public/full?start-min={StartTime}&start-max={endTime}&alt=json-in-script&callback=?";
dataType: 'json',
timeout: 3000,
success: function( data ) { ProcessData(data);},
});
Within function ProcessData(data) I have the following statement:
StartTime = new Date(data.feed.entry[i].gd$when[j].startTime);
which stores in StartTime a Date() object with the date a particular event starts. Google normally uses ISO 8601 time format: YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00) and this works just fine. However, for "All Day" events the format is only in the form: YYYY-MM-DD (eg 1997-07-16) (Which is allowed by W3 http://www.w3.org/TR/NOTE-datetime) and in this case new Date() will interpret this as GMT. This is, will correct that particular date to your local time zone even if the event was already created in your local time-zone. In my particular case, when retrieving an "All Day" event on, say, April 7th 2014 happening in my time zone would return a string as if it was 5 hours earlier
new Date("2014-04-07")
returns Sun Apr 06 2014 19:00:00 GMT-0500 (CDT) which is off by 5 hours. (See the following question for more details on date parsing)
Have you ever had to deal with this issue when using Google Calendar? And if so, how did you solve it? Should I be using a different method instead of new Date() that would actually account for the time zone?
Google's JSON response contains a parameter feed.timezone, which contains the Olson's Time Zone ID but I'd need a way to convert (hopefully another Ajax call or something like that) that ID into an actual offset. I found the following question in this forum but the problem with this is that the parameter this API needs is the actual city and not the time Zone ID making me then to somehow make the translation from time zone ID to a city to pass to the URL string.
Any help would be appreciated!
When you say ISO 8601 strings with an offset "work just fine", are you leaving parsing up to the Date constructor, or are you doing it yourself? Some browsers won't correctly parse an ISO string, and more won't correctly parse a string with an offset. There's an answer here that shows how to parse an ISO string with offset for all browsers.
In regard to how to deal with dates, that is an issue that only has a business logic answer. If it is interpreted as an ISO 8601 string, then in any timezone that is west of Greenwich (or more than an hour west during its daylight saving time), it will result in a date one day before. If you wish to treat it as a local date, you'll need to first test the string to see if it's just a date and if so, treat it as local, e.g.
if (/^\d{4}-\d{2}-\d{2}/.test(dateString) {
// treat as date
} else {
// treat as date and time
}
Parsing the string as a local date is pretty simple:
// Expect a date string in ISO 8601 format YYYY-MM-DD
// Date is created as a local date
function parseLocalDateTime(s) {
s = s.split(/\D+/g);
return new Date(s[0], --s[1], s[2]);
}

Categories