let's say I have this date as input :
var _dateA = 2018-11-15T11:13:26.687Z
If I'm doing, whatever,
var _dateB = new Date(_date)
or
var _dateB = moment(_date)
I get this as result ==>
_dateB = Thu Nov 15 2018 12:13:26 GMT+0100 (heure normale d’Europe centrale)
I understood that there's timezone trouble, but how can I get a Date object or Moment object, without having this one hour more?
Wanted result => Thu Nov 15 2018 11:13:26 GMT+0100
Current result => Thu Nov 15 2018 12:13:26 GMT+0100
You need to use Date.toUTCString() that converts date to string, using the UTC time zone
var _dateA = '2018-11-15T11:13:26.687Z';
var _dateB = new Date(_dateA);
console.log(_dateB.toUTCString());
When you "output" a Date object via console.log(), alert(), etc the toString() method is used by default, converting the date object to a local timezone string for display (which is why you are seeing your date in your local time).
Parsing date strings with the Date constructor is not recommended (although, I suspect that most browsers probably handle ISO 8601 dates, like the one in your question, fairly well) - see the dateString parameter note here. So, if you need to construct a date object as well as output a date string, then you could parse the ISO 8601 string with split() using a regex character set for multiple delimiters, then construct a UTC date object with new Date(Date.UTC(...)). You could also do this with moment.js but the below should illustrate what is happening in a bit more detail.
For example:
const text = '2018-11-15T11:13:26.687Z'
const [y, m, d, hh, mm, ss, ms] = text.split(/[-T:.Z]/);
const date = new Date(Date.UTC(y, m - 1, d, hh, mm, ss, ms));
console.log(date.toLocaleString()); // date string in local timezone
console.log(date.toUTCString()); // UTC date string
console.log(JSON.stringify(date)); // ISO 8601 date string in most browsers
Related
I really just have a simple question. I want to convert a string in yyyy-mm-dd to a date object in javascript. This seems simple enough. You can just do the following.
var date = new Date('2020-04-08');
But in this case, javascript considers the date '2020-04-08' as UTC midnight. So the actual date that is returned to me is the following.
Tue Apr 07 2020 17:00:00 GMT-0700 (Pacific Daylight Time)
I know I can create a date in the following format
var date = new Date(2020, 3, 8);
Wed Apr 08 2020 00:00:00 GMT-0700 (Pacific Daylight Time)
But it looks like too much hassle to extract the year, month and date from the already nicely formatted date string. Isn't there a simple way to convert yyyy-mm-dd string to a date object without it being treated as UTC date?
So in the simplest terms, my question is how do I tell the date constructor that the date I am passing is not a UTC date but a local date.
Simply append 'T00:00:00' to your date string.
const dateString = '2020-04-08'
const timeString = 'T00:00:00'
const date = new Date(dateString + timeString);
console.info(date.toString())
From the documentation
Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
I am getting a date as a string '2018-10-15 00:00:00.000', then converting it to a date using new Date('2018-10-15 00:00:00.000').
I am persisting this date to a database (with API) and it is saving the data as 2018-10-15 **04**:00:00.000. Note the 4 am time. The API gets the date time as 4:00 am.
In my angular application, the object that holds this date is defined as Date type.
meeting_date: Date;
This is from the console.
dt = new Date('2018-10-15 00:00:00.000')
Mon Oct 15 2018 00:00:00 GMT-0400 (Eastern Daylight Time)
JSON.stringify(dt)
""2018-10-15T04:00:00.000Z""
I want to save the date as 2018-10-15 00:00:00.000. What am I doing wrong?
If the date input string you are getting represents UTC, then you probably want to create the Date object in UTC (your current approach is creating the Date object in local time on the client machine, which is why the EDT offset is affecting the datetime you are storing in your db). Also, you should be aware that Date() is not recommended for parsing date strings due to browser inconsistencies.
Following is an example using some simple regex to parse the string and create the Date object in UTC:
const str = '2018-10-15 00:00:00.000';
const [y, m, d, hh, mm, ss, ms] = str.match(/\d+/g);
const date = new Date(Date.UTC(y, m - 1, d, hh, mm, ss, ms));
console.log(JSON.stringify(date));
// date as UTC string
console.log(date.toUTCString());
// date as local string
console.log(date.toString());
I just came across this format of start and end in the codebase which is probably the starting and ending date and time.However, I could not figure out this.
I know how to generate date and time in javascript but I need to generate it in this format to be able to fetch data from API.
Here is the format.
start : '2018-06-20T11:44:21.938Z',
end : '2018-07-20T11:44:21.938Z',
At the same time, I would like to know how to get date and time with exact this format?
It is ISO format of the date. You can use toISOString() method to achieve it:
// current date
var date = new Date();
console.log(date);
console.log(date.toISOString());
let date = new Date( Date.parse('2018-06-20T11:44:21.938Z'));
To retrieve date & time separately.
date.toLocaleDateString();
date.toLocaleTimeString()'
To convert any date object to your desired format (ISO Dates):
var date = new Date();
date.toISOString();
var date = new Date(Date.parse('2018-06-20T11:44:21.938Z'));
It's ISO 8601 format.
Check this:
https://en.wikipedia.org/wiki/ISO_8601
Have a look at toISOString() in MDN
var event = new Date('05 October 2011 14:48 UTC');
console.log(event.toString());
// expected output: Wed Oct 05 2011 16:48:00 GMT+0200 (CEST)
// (note: your timezone may vary)
console.log(event.toISOString());
// expected output: 2011-10-05T14:48:00.000Z
That is the ISO date format.
similar to this:
How do I output an ISO 8601 formatted string in JavaScript?
Here is code to produce it.
function myFunction() {
var d = new Date();
var n = d.toISOString();
document.getElementById("demo").innerHTML = n;
}
<button onclick="myFunction()">convert to ISO date format</button>
<p id="demo"></p>
It is an ISO date. Check this link for some info:
https://www.w3schools.com/js/js_date_formats.asp
var istDate = new Date(); // will return: Wed Sep 05 2018 17:50:39 GMT+0530 (India Standard Time)
var isoDate = istDate.toISOString(); // will return in ISO format i.e. "2018-09-05T12:20:39.732Z"
var dateString = istDate.toDateString(); // will return in format: "Wed Sep 05 2018"
Browser console will provide suggestions for various methods of Date Object for extracting day, month, year, etc from the new Date()
when i select a date say 12/03/2014 it retuns Tue Dec 02 2014 16:00:00 GMT-0800 (Pacific Standard Time) one day before what i entered?
<script>
function getAge() {
var today = new Date();
var birthDate = new Date(document.forms["name"]["birth"].value);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate()+1)) {
age--;
}
document.getElementById('age').innerHTML = birthDate;
}
</script>
<form name='name' onsubmit='return false'>
<input type="date" name="birth">
<p id='age'></p>
<button onclick='getAge()'>check</button>
</form>
This is an old question, but I wanted to resurrect it since this was the first result in my Google query and the accepted answer doesn't really answer the question well. So I'm providing a bit more information for others to stumble upon.
There are several convenience methods in the Date object which may be of help to those trying to work around this little JavaScript quirk.
It seems to me that there is no way to change a Date object timezone offset programmatically, and it must be done using String manipulation, which is truly undesirable, but there is no other way. The Date object constructor always uses the local machine timezone when interpreting dates, and this cannot be changed. As such, you must understand that when you create a Date which essentially ignores the timezone, the altered Date object will represent a different moment in time from the original Date. The new Date object will automatically adopt the local machine's timezone but it will use the (year, month, date, hour, min, sec, ms) which you designate in either the individual constructor parameters or string parameter of the Date class (of the two options below).
I found two ways to work around this and produce a correct date from a type="date" input field. Please use the one you feel is more effective or appropriate for your solution. Personally, I prefer using OPTION B since it is more programatic than string manipulation and probably a bit more reliable as such. It's also a bit simpler.
OPTION A: UTC date string manipulation
getUTCDate - returns the day of the month (from 1 to 31) of the date object, according to universal time. The UTC methods calculate their date assuming that the date object is of local time and date.
getUTCString - converts a Date object to a string, according to universal time.
NOTE: The Date constructor reverts back to local timezone. Therefore, you cannot build a new Date with the getUTCString() value and expect to get the correct date from the input field.
You can solve this issue by using getUTCDate() and calling dateObject.setDate(dateObject.getUTCDate());, which corrects only the date portion of the object, so you will need to correct the month and year as well using dateObject.setMonth(dateObject.getUTCMonth()); and dateObject.setFullYear(dateObject.getUTCFullYear()); respectively. Or you can remove everything after the "GMT" portion of the getUTCString() value, which will give you a string without a timezone designation. You can then use the string to create a new Date object, which will default to the client's timezone.
//convert to UTC to avoid "date minus one" issues where the supplied date is interpreted incorrectly as
//the previous date.
date = new Date(document.getElementById('date').value);
console.log("original date: " + date.toString());
console.log("UTC date string: " + date.toUTCString());
//produces local machine timezone, and therefore incorrect date value
date = new Date(date.toUTCString());
console.log("UTC date string Date constructor: " + date.toString());
utcDate = new Date(utcString.substr(0, utcString.indexOf("GMT")));
console.log("UTC date string Date constructor (without 'GMT*'): " + utcDate.toString());
console.log("UTC date number: " + date.getUTCDate());
date.setDate(date.getUTCDate());
date.setMonth(date.getUTCMonth());
date.setFullYear(date.getUTCFullYear());
console.log("UTC modified date: " + date.toString());
Output:
original date: Fri Jan 29 2021 23:16:11 GMT-0600 (Central Standard Time)
UTC date string: Sat, 30 Jan 2021 05:16:11 GMT
UTC date string Date constructor: Fri Jan 29 2021 23:16:11 GMT-0600 (Central Standard Time)
UTC date string Date constructor (without 'GMT*'): Sat Jan 30 2021 23:16:11 GMT-0600 (Central Standard Time)
UTC date number: 30
UTC modified date: Sat Jan 30 2021 23:16:11 GMT-0600 (Central Standard Time)
OPTION B: provide all UTC parameters to Date constructor
(see also: Create a Date with a set timezone without using a string representation)
example:
date = new Date(document.getElementById('date').value);
console.log("original date: " + date.toString());
date = new Date(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
date.getUTCHours(),
date.getUTCMinutes(),
date.getUTCSeconds(),
date.getUTCMilliseconds());
console.log("Date with UTC parameters: " + date.toString());
Output:
original date: Fri Jan 29 2021 23:04:03 GMT-0800 (Pacific Standard Time)
Date with UTC parameters: Sat Jan 30 2021 07:04:03 GMT-0800 (Pacific Standard Time)
the incorrect date is due to your timezone settings. It's GMT-8.
Consider using UTC: http://www.w3schools.com/jsref/jsref_toutcstring.asp
Given the volume of Timezone questions, I would have thought to be able to find the answer to this issue, but haven't had any success.
Is there a way using moment.js to parse an ISO-8601 string but have it parsed in my local timzeone? Essentially I want to ignore the timezone information that is supplied in the ISO string.
For example, if I am in EDT timezone:
var x = moment( "2012-12-31T00:00:00+0000" );
will give me:
"2012-12-30T19:00:00-5000"
I'm looking to ignore the timezone info and just have it give me a moment equivalent of "2012-12-31T00:00:00-5000" local time (EDT).
I don't think you really want to ignore the offset. That would ultimately just be replacing the offset you provided with one from your local time zone - and that would result in a completely different moment in time.
Perhaps you are just looking for a way to have a moment retain the time zone it was given? If so, then use the moment.parseZone function. For example:
var m = moment.parseZone("2012-12-31T00:00:00+0000");
var s = m.format(); // "2012-12-31T00:00:00+00:00"
You could also achieve this with moment.utc. The difference is that moment.parseZone will retain whatever offset you give it, while moment.utc will adjust to UTC if you give it a non-zero offset.
I solved this by supplying a format as the second argument, and using Moment's method of escaping characters, and wrapped square brackets around the timezone.
moment("2016-01-01T05:00:00-05:00", "YYYY-MM-DDTHH:mm:ss[Z]").startOf("hour").format()
This will still create moment objects using your local time zone, but it won't do any sort of auto-timezone calculation. So the above example will give you 5am regardless of timezone supplied.
I know I'm late to the party, I had the same question and my searches didn't bring me any closer. I broke down and read the documentation and there is an option in moment for a String + Format:
String + Format docs
moment(String, String);
moment(String, String, String);
moment(String, String, Boolean);
moment(String, String, String, Boolean);
and more words, then this:
Unless you specify a time zone offset, parsing a string will create a date in the current time zone.
moment("2010-10-20 4:30", "YYYY-MM-DD HH:mm"); // parsed as 4:30 local time
moment("2010-10-20 4:30 +0000", "YYYY-MM-DD HH:mm Z"); // parsed as 4:30 UTC
The part that gave me pause was the example that was used to parse local time omitted the +0000, which lead me to think the input string needed to have that removed, but it doesn't.
example:
var time = "2012-12-31T00:00:00+0000";
var x = moment(time); // Sun Dec 30 2012 19:00:00 GMT-0500
var y = moment(time,'YYYY-MM-DD'); //Mon Dec 31 2012 00:00:00 GMT-0500
You can ignore the browser's timezone completely by creating a new moment using moment.utc() instead of moment().
For example, if you are trying to work purely with a UTC date/time of the browser's current time but want to discard its timezone data, you can recreate the browser's current time into a UTC format using the following:
let nowWithTimezone = moment();
let nowInUtc = moment.utc(nowWithTimezone.format('MM/DD/YYYY HH:mm'), 'MM/DD/YYYY HH:mm');
Further documentation on moment.utc(): https://momentjs.com/docs/#/parsing/utc/
If you know for sure your input string is in the ISO-8601 format, you could just strip off the last 5 digits and use that in the Moment constructor.
var input = "2012-12-31T00:00:00+0000"
input = input.substring(0, input.length-5)
moment(input).toString()
> "Mon Dec 31 2012 00:00:00 GMT-0600"
There are valid reasons to do what the OP is asking for. The easiest way to do this with Moment is using its parseZone(date) method. No futzing around with string manipulation or multiple calls. It effectively parses the date string as though it were in the browser's local time zone.
This is difficult task to do with MomentJS, it will basically depend as well on your current timezone.
Documentation as well is vague for this specific task, the way I solved the issue on my side was by adding hours to the date before converting it to JSON format.
var dt = moment("Sun Sep 13 2015 00:00:00 GMT-0400", "ddd MMM DD YYYY HH:mm:ss GMT-0400", false);
var date = dt.add(2, 'hour').toJSON();
console.log(date); //2015-09-13T00:00:00.000Z
Momentjs default logic will format the given time with local timezone. To format original date, I wrote a function:
https://github.com/moment/moment/issues/2788#issuecomment-321950638
Use moment.parseZone to convert without taking into account the timezone.
const moment = require('moment')
const dateStr = '2020-07-21T10:00:00-09'
const date = moment.parseZone(dateStr)
console.log(date.format('MM-DD-YY HH:mm A')) // 07-21-20 10:00 AM
Try here link to docs
The best way is to use:
dt = moment("Wed Sep 16 2015 18:31:00 GMT-0400", "ddd MMM DD YYYY HH:mm:ss GMT-0400",true);
And to display convert again to desired timezone:
dt.utcOffset("-04:00").toString()
output > Wed Sep 16 2015 18:31:00 GMT-0400