Why does ISO date in Mongodb display one day earlier? - javascript

The stored date looks like this:
...
"date_of_birth" : ISODate("1920-01-02T00:00:00Z"),
...
Using moment, it is formatted in the model (in order to populate the input for updating the document) like this:
AuthorSchema
.virtual('date_of_birth_update_format')
.get(function(){
// format in JavaScript date format (YYYY-MM-DD) to display in input type="date"
return this.date_of_birth ? moment(this.date_of_birth).format('YYYY-MM-DD') : '';
});
Retrieved from the collection and displayed, it displays as one day earlier like this:
01/01/1920
I would appreciate any help to resolve this.

The date from mongo is always in GMT, and your server might be in other timezone. You need to convert date to GMT before formatting.
var moment = require("moment-timezone")
AuthorSchema.virtual('date_of_birth_update_format').get(function(){
return this.date_of_birth ? moment(this.date_of_birth).tz('GMT').format('YYYY-MM-DD') : '';
});

The Z in the ISO 8601 format implies 'GMT' i.e. 1920-01-02T00:00:00+0000. Moment will take your timezone into consideration. If you are in the continental US, your time zone offset is -0400—-0800.
1920-01-02T00:00:00Z = 1920-01-01T6:00:00-0600 In Pacific Standard Time for example.

It depends on the time zone which you are in for example am in India so GMT for me is +5:30 so whenever I retrieve from db I would add up 5:30 to time so that it matches the date and to answer why it storing it a day before because it stores date in ISO format that's why

Same problem here. I was using EJS to show the date retrieved from the MongoDB database. I'm not sure if the problem is with EJS, but I solved it like this:
All I had to do was to set the timeZone to GMT in the front-end:
date.toLocaleString("pt-BR", {timeZone:"GMT", day: "numeric", month: "numeric", year:"numeric"});

Related

Convert HTML Date to Mysql Format

I am using a bootstrapdatetimepicker as well as moment.js
When i call the following
var starteventtime= ($('#startdatetime').data('DateTimePicker').date());
I get a date similar to
Wed Mar 27 2019 00:00:00 GMT+0000
I also have the option for the user to save their own format of the date. So any code will have to take this into consideration.
<?php
$datetimeformat = 'DD/MM/YYYY HH:mm';
?>
$(function() {
$('#startdatetime').datetimepicker({
format: '<?php echo $datetimeformat; ?>'
});
How do i parse this on the client side with javascript to get Mysql formatted date so when the data is serialized it will be in a format ready for insertion into the database like below
2019-03-27 00:00:00
I am quite certain whatever the date time picker returns is a Date object and not a string (if it isn't, use another picker, because this one is useless).
When you have the Date object, you can format that however you want to insert it into your database. For example with the answer given here: How to format a JavaScript date
You should look into converting your dates into a standard Unix timestamp. Its super easy in every environment you're working in (Mysql, php, javascript). For example, in javascript Date.now() returns the current time as a Unix timestamp. Look up how to do that for the other places you're working with time. With that as a standard, you can just pass around the timestamps for your dates without having to worry about formatting until you're ready to display them.
Thanks for the advice , i used
moment($('#startdatetime').data('DateTimePicker').date()).format("YYYY/MM/DD HH:mm"));
to convert it to an object that was in mysql format.

moment-timezones.js, how to convert date in spesific timezone to utc, disregarding my local timezone?

my system uses timezone UTC+03:00 ,
im trying to get a date in string format, represented by NY timezone,
and convert it to a Date object in utc
const dateInNY = moment.tz(xlsxDate, "M/D/YYYY h:mm a", "America/New_York")
.tz("Z").toDate();
doesnt work correctly
how am i even suppose to convert to utc time?
-----------edit---------------
i got it to work, using the timezone "Africa/Accra" , where UTC offset is 0, and ther is no daylight savings time:
moment.tz(xlsxDate, "M/D/YYYY h:mm a", "America/New_York").tz("Africa/Accra")
but this solution is a bad workaround, and if the government of Accra decide to change the time laws, will stop working!
is there a way to set the utc offset to 0 in momentjs-timezones?
As Álvaro González mentioned, that Date object does not contain Time zone information.
I do the following:
new Date(moment.tz(date, currentTimezone).tz(newTimezone).format('YYYY/MM/DD HH:mm:ss'))
where date is a date object or a string (e.g. '2017-10-30 16:30:00.0000')
so, I change date from currentTimezone to newTimezone and after that new Date object will be returned
Let's change '2017-10-30 16:30:00.0000' from UTC to America/Toronto (UTC-4)
new Date(moment.tz(date, 'UTC').tz('America/Toronto').format('YYYY/MM/DD HH:mm:ss'))
And I got
Mon Oct 30 2017 12:30:00 GMT+0400
GMT+0400 is my timezone and console.log() just shows it with any
date object and it can mislead you. Please, don't look at the this
timezone.
Let's change '2017-10-30 16:30:00.0000' from Europe/Samara (UTC+4) to America/Toronto (UTC-4)
new Date(moment.tz('2017-10-30 16:30:00.0000', 'Europe/Samara').tz('America/Toronto').format('YYYY/MM/DD HH:mm:ss'))
Firstly, moment.tz undertands that date has no timezone information and associate with Europe/Samara (UTC+4)
timezone. After that computes difference between new and old
timezone (it's -8 hours in this case)
And returns result
Mon Oct 30 2017 08:30:00 GMT+0400
And answer on your question
If xsltDate is a date object or string which do not contain timezone information
dateUTC = new Date(moment.tz(xlsxDate, "America/New_York").tz("UTC").format('YYYY/MM/DD HH:mm:ss'));
If xsltDate contain timezone information (e.g.'2013-06-01T00:00:00-04:00'), then no need to tell moment.tz which timezone xlsxDate has, just mention a new timezone
dateUTC = new Date(moment.tz(xlsxDate, "UTC").format('YYYY/MM/DD HH:mm:ss'));
Short answer is that you cannot.
The .toDate() method of the Moment library returns a native Date object. Such objects do not keep memory of any specific time zone (that's one of the reasons to use Moment in the first place), they just keep track of the exact time moment represented and merely pick a time zone when formatting to string, which is either UTC or the browser's time zone (not an arbitrary one).
The long answer is that you're probably getting correct results but are printing them with a method that uses the browser's time zone.
i found a function that does what i was trying to do, it belongs to the momentjs library itself: utcOffset(n) sets the offset to n.
(i also had to explicitly write the date string format correctly, thanks VincenzoC)
this is the code i was trying to write:
const dateInNY = moment.tz(xlsxDate, "M/D/YYYY h:mm a", "America/New_York");
const dateUTC = dateInNY.utcOffset(0).toDate();
however, the toDate function changes the timezone to my local timezone anyway, so .utcOffset(0) is redundat, and i can just use moment this way:
const dateInNY = moment.tz(xlsxDate, "M/D/YYYY h:mm a", "America/New_York");
const dateUTC = dateInNY.toDate();
and change the Date objects date to utc time later (in my case, the JSON.stringify stuff i use later does that for me)

How to parse date string from database without time shift?

I am getting 2016-07-13T00:00:00.000Z string from database and converting it to MM/DD/YYYY format with moment.js like this:
result = moment('2016-07-13T00:00:00.000Z').format('MM/DD/YYYY');
which prints 07/12/2016 but I was expecting 07/13/2016.
Local Linux timezone is America/New_York. date command prints this Mon Jul 4 04:28:19 EDT 2016
The date that you have is in UTC, as signified by the z at the end.
When you use the default moment constructor, moment(), it converts the time you pass it from the specified offset (in this case UTC) to the local time of the machine. This is why your date is changing. Because this is a UTC date, to keep it exactly the same you can use moment.utc():
moment.utc('2016-07-13T00:00:00.000Z').format('MM/DD/YYYY');
"07/13/2016"
Alternately, parseZone would work as well:
moment.parseZone('2016-07-13T00:00:00.000Z').format('MM/DD/YYYY');
"07/13/2016"
For more information about all of the constructor functions in moment, see the parsing guide
or this blog post
You should use momentjs timezone : http://momentjs.com/timezone/
yourdate = moment.tz("2016-07-13T00:00:00.000Z", "America/New_York");
alert(yourdate.format('MM/DD/YYYY'));
This should give you the correct date in output.

Adding +GMT in Javascript

Good day, I would like to ask how can I add any timezone in my date object?
My scenario is I have created a date picker and time picker and they will generate a DateTime Object looking like "01/02/2003 4:56 PM" I just need to add the GMT +/- (Timezone) in the date time object so it can look like "01/02/2003 4:56 PM GMT + 0700" and my backend will process the conversion to utc.
Is it possible? Thank you and good day.
You can use new Date("01/02/2003 4:56 PM") which will return time zone information.

jQuery / Javascript - convert datetime to user's timezone datetime

I updated this question
I would like to transform a datetime to the equivalent datetime in the country(timezone) user is located to.
I have datetime in this format which is UTC/GMT:
Oct 31, 2012 08:10:02
now, according with the user's client timezone i would like to convert that datetime using the current browser/client user's timezone
how can i do that?
If I understand correctly, you want to be able to set the end date for the countdown in UTC time, as opposed to the local time of the browser. You don't need to modify the plugin to do this. You just want the setUTC... methods in the Date object. Take a look here: http://www.w3schools.com/jsref/jsref_obj_date.asp.
For example:
var endofworld = new Date(0);
endofworld.setUTCFullYear(2012);
endofworld.setUTCMonth(11);
endofworld.setUTCDate(21);
$('.countdown').countdown({ date: endofworld });

Categories

Resources