adding minutes to a date (javascript) invalid date - javascript

I've this function to add minutes to a date in javascript
function addMinutes(date, minutes) {
var DateObject = new Date(date);
var modifiedDate = DateObject.getTime() + minutes * 60000;
return date = modifiedDate;
}
The script works perfectly on most of my pages but on the current page i'm working on I've this date: 2014-06-07 01:00:00
This works only in google chrome.. I've that browsers like IE/Safari are not able to work with YYYY/MM/DD format.
I've tried to parse it with Date, but this is kinda new for me and I'm not sure what i'm doing wrong.

here's a fixed copy of the orig with suggestions implemented:
function addMinutes(date, minutes) {
var DateObject = new Date(String(date).replace(/\ /g,"T")+"Z"),
modifiedDate = DateObject.getTime() +
(minutes* 60000) +
(new Date(DateObject).getTimezoneOffset()*60*1000) ;
return date = modifiedDate;
}
new Date(addMinutes("2014-06-07 01:00:00", 15)).toLocaleString();
// shows: "6/7/2014 1:15:00 AM"

There are two different problems here that you should mentally separate:
Parsing a string in the particular format of YYYY-MM-DD hh:mm:ss to a Date object.
Adding minutes to a Date object.
Parsing the String
You should be aware that the parsing behavior when you pass a string to the Date constructor is implementation specific, and the implementations vary between browser vendors.
In general, when dashes (-) are present, the values are treated as UTC, and when slashes (-) are present, the values are treated as local to the time zone where the code is running.
However, this only applies when either a time is not present, or when the date and time components are separated with a T instead of with a space. (YYYY-MM-DDThh:mm:ss)
When a space is used to separate date and time components, some browsers (like Chrome) will treat it as local time, but other browsers (like IE and Firefox) will consider it an invalid date.
Replacing the space with a T will allow the date to be parsed, but if that's all you do, then Chrome will treat it as UTC, while IE and Firefox will treat it as local time.
If you also add the trailing Z, (YYYY-MM-DDThh:mm:ssZ) then all browsers will parse it as UTC.
If you want a format that all browsers will recognize as local time, there is only one, and it's not ISO standard: YYYY/MM/DD hh:mm:ss. Thus, you might consider:
var s = "2014-06-07 01:00:00";
var dt = new Date(s.replace(/-/g,'/'));
Adding Minutes
This is much more straightforward:
dt.setMinutes(dt.getMinutes() + 15);
That will simply mutate the Date value to add 15 minutes. Don't worry about overflow - if getMinutes returns 55, setting 70 minutes will properly add 1 hour and 10 minutes.
A Better Solution
Moment.js removes all of the guesswork about parsing variations, and gives you a much cleaner API. Consider:
// parse a string using a specific format
var m = moment("2014-06-07 01:00:00","YYYY-MM-DD HH:mm:ss");
// adding time
m.add(15, 'minutes');
// format the output as desired, with lots of options
var s = m.format("L h:mm:ss A");

Related

Jquery countdown in UTC [duplicate]

Suppose a user of your website enters a date range.
2009-1-1 to 2009-1-3
You need to send this date to a server for some processing, but the server expects all dates and times to be in UTC.
Now suppose the user is in Alaska. Since they are in a timezone quite different from UTC, the date range needs to be converted to something like this:
2009-1-1T8:00:00 to 2009-1-4T7:59:59
Using the JavaScript Date object, how would you convert the first "localized" date range into something the server will understand?
Simple and stupid
var date = new Date();
var now_utc = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(),
date.getUTCDate(), date.getUTCHours(),
date.getUTCMinutes(), date.getUTCSeconds());
console.log(new Date(now_utc));
console.log(date.toISOString());
The toISOString() method returns a string in simplified extended ISO
format (ISO 8601), which is always 24 or 27 characters long
(YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ,
respectively). The timezone is always zero UTC offset, as denoted by
the suffix "Z".
Source: MDN web docs
The format you need is created with the .toISOString() method. For older browsers (ie8 and under), which don't natively support this method, the shim can be found here:
This will give you the ability to do what you need:
var isoDateString = new Date().toISOString();
console.log(isoDateString);
For Timezone work, moment.js and moment.js timezone are really invaluable tools...especially for navigating timezones between client and server javascript.
Here's my method:
var now = new Date();
var utc = new Date(now.getTime() + now.getTimezoneOffset() * 60000);
The resulting utc object isn't really a UTC date, but a local date shifted to match the UTC time (see comments). However, in practice it does the job.
Update: This answer is a quick-and-dirty way to get the UTC date when calling utc.toString(), utc.toLocaleString(), etc. Though, there are better solutions, in particular nowadays with modern browsers, and I should work on an improved answer. Basically, now.toISOString() (IE 9+) is what you want to use.
Convert to ISO without changing date/time
var now = new Date(); // Fri Feb 20 2015 19:29:31 GMT+0530 (India Standard Time)
var isoDate = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString();
//OUTPUT : 2015-02-20T19:29:31.238Z
Convert to ISO with change in date/time(date/time will be changed)
isoDate = new Date(now).toISOString();
//OUTPUT : 2015-02-20T13:59:31.238Z
Fiddle link
Date.prototype.toUTCArray= function(){
var D= this;
return [D.getUTCFullYear(), D.getUTCMonth(), D.getUTCDate(), D.getUTCHours(),
D.getUTCMinutes(), D.getUTCSeconds()];
}
Date.prototype.toISO= function(){
var tem, A= this.toUTCArray(), i= 0;
A[1]+= 1;
while(i++<7){
tem= A[i];
if(tem<10) A[i]= '0'+tem;
}
return A.splice(0, 3).join('-')+'T'+A.join(':');
}
Another solution to convert to UTC and keep it as a date object:
(It works by removing the ' GMT' part from the end of the formatted string, then putting it back into the Date constructor)
const now = new Date();
const now_utc = new Date(now.toUTCString().slice(0, -4));
console.log(now_utc.toString()); // ignore the timezone
I needed to do this to interface with a datetime picker library. But in general it's a bad idea to work with dates this way.
Users generally want to work with datetimes in their local time, so you either update the server side code to parse datetime strings with offsets correctly, then convert to UTC (best option) or you convert to a UTC string client-side before sending to the server (like in Will Stern's answer)
Browsers may differ, and you should also remember to not trust any info generated by the client, that being said, the below statement works for me (Google Chrome v24 on Mac OS X 10.8.2)
var utcDate = new Date(new Date().getTime());
edit: "How is this different than just new Date()?" see here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
If no arguments are provided, the constructor creates a JavaScript Date object for the current date and time according to system settings.
Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date(Date.UTC(...)) with the same arguments. (note: Date.UTC() returns the number of millisecond since 1970-01-01 00:00:00 UTC)
Adding the 60000 * Date.getTimezoneOffset() as previous answers have stated is incorrect. First, you must think of all Dates/Times as already being UTC with a timezone modifier for display purposes.
Again, browsers may differ, however, Date.getTime() returns the number of milliseconds since 1970-01-01 UTC/GMT. If you create a new Date using this number as I do above, it will be UTC/GMT. However, if you display it by calling .toString() it will appear to be in your local timezone because .toString() uses your local timezone, not the timezone of the Date object it is called on.
I have also found that if you call .getTimezoneOffset() on a date, it will return your local timezone, not the timezone of the date object you called it on (I can't verify this to be standard however).
In my browser, adding 60000 * Date.getTimezoneOffset() creates a DateTime that is not UTC. However when displayed within my browser (ex: .toString() ), it displays a DateTime in my local timezone that would be correct UTC time if timezone info is ignored.
My solution keeps the date the same no matter what timezone is set on the client-side. Maybe someone will find it useful.
My use case:
I'm creating a todo app, where you set date of your task. This date should remain constant no matter what timezone you're in.
Example. You want to call your friend at 8 am on June 25th.
You create this task 5 days before (June 20th) while you're in China.
Then, on the same day, you fly to New York for a few days.
Then on June 25th, while you're still in New York, you wake up at 7:30 am (which means you should receive task notification in 30 mins (even tho it's 1:30 pm already in China where you were when creating the task)
So the task is ignoring the timezone. It means 'I want to do it at 8 am in whatever timezone I'll be in'.
What I do is let's say 'I assume you're always in London Timezone - UTC'.
What it means is - when the user picks some date in her/his Timezone - I convert this date to the same date in UTC. ie. You pick 8 am in China, but I convert it to 8 am in UTC.
Then - next time you open the app - I read the date saved in UTC and convert it to the same date in your current timezone - eg. I convert 8 am in UTC to 8 am in the New York timezone.
This solution means that the date can mean something else depending on where you are when setting it and where you're reading it, but it remains constant in a way that it 'feels' like you're always in the same timezone.
Let's write some code:
First - we have 2 main functions for converting from/to UTC ignoring timezone:
export function convertLocalDateToUTCIgnoringTimezone(date: Date) {
const timestamp = Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds(),
);
return new Date(timestamp);
}
export function convertUTCToLocalDateIgnoringTimezone(utcDate: Date) {
return new Date(
utcDate.getUTCFullYear(),
utcDate.getUTCMonth(),
utcDate.getUTCDate(),
utcDate.getUTCHours(),
utcDate.getUTCMinutes(),
utcDate.getUTCSeconds(),
utcDate.getUTCMilliseconds(),
);
}
Then, I save/read this date like:
function saveTaskDate(localDate: Date) {
// I convert your local calendar date so it looks like you've picked it being in UTC somewhere around London
const utcDate = convertLocalDateToUTCIgnoringTimezone(localDate);
api.saveTaskDate(utcDate);
}
function readTaskDate(taskUtcDate: Date) {
// I convert this UTC date to 'look in your local timezone' as if you were now in UTC somewhere around london
const localDateWithSameDayAsUTC = convertUTCToLocalDateIgnoringTimezone(taskUtcDate);
// this date will have the same calendar day as the one you've picked previously
// no matter where you were saving it and where you are now
}
var myDate = new Date(); // Set this to your date in whichever timezone.
var utcDate = myDate.toUTCString();
Are you trying to convert the date into a string like that?
I'd make a function to do that, and, though it's slightly controversial, add it to the Date prototype. If you're not comfortable with doing that, then you can put it as a standalone function, passing the date as a parameter.
Date.prototype.getISOString = function() {
var zone = '', temp = -this.getTimezoneOffset() / 60 * 100;
if (temp >= 0) zone += "+";
zone += (Math.abs(temp) < 100 ? "00" : (Math.abs(temp) < 1000 ? "0" : "")) + temp;
// "2009-6-4T14:7:32+10:00"
return this.getFullYear() // 2009
+ "-"
+ (this.getMonth() + 1) // 6
+ "-"
+ this.getDate() // 4
+ "T"
+ this.getHours() // 14
+ ":"
+ this.getMinutes() // 7
+ ":"
+ this.getSeconds() // 32
+ zone.substr(0, 3) // +10
+ ":"
+ String(temp).substr(-2) // 00
;
};
If you needed it in UTC time, just replace all the get* functions with getUTC*, eg: getUTCFullYear, getUTCMonth, getUTCHours... and then just add "+00:00" at the end instead of the user's timezone offset.
date = '2012-07-28'; stringdate = new Date(date).toISOString();
ought to work in most newer browsers. it returns 2012-07-28T00:00:00.000Z on Firefox 6.0
My recommendation when working with dates is to parse the date into individual fields from user input. You can use it as a full string, but you are playing with fire.
JavaScript can treat two equal dates in different formats differently.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
Never do anything like:
new Date('date as text');
Once you have your date parsed into its individual fields from user input, create a date object. Once the date object is created convert it to UTC by adding the time zone offset. I can't stress how important it is to use the offset from the date object due to DST (that's another discussion however to show why).
var year = getFullYear('date as text');
var month = getMonth('date as text');
var dayOfMonth = getDate('date as text');
var date = new Date(year, month, dayOfMonth);
var offsetInMs = ((date.getTimezoneOffset() * 60) // Seconds
* 1000); // Milliseconds
var utcDate = new Date(date.getTime + offsetInMs);
Now you can pass the date to the server in UTC time. Again I would highly recommend against using any date strings. Either pass it to the server broken down to the lowest granularity you need e.g. year, month, day, minute or as a value like milliseconds from the unix epoch.
If you are dealing with dates a lot, it's worth using moment.js (http://momentjs.com). The method to convert to UTC would be:
moment(yourTime).utc()
You can use format to change your date to any format you want:
moment(yourTime).utc().format("YYYY-MM-DD")
There is offset options in moment as well but there is an additional complementary library for dealing with timezone (http://momentjs.com/timezone/). The time conversion would be as simple as this:
moment.tz(yourUTCTime, "America/New_York")
I've found the jQuery Globalization Plugin date parsing to work best. Other methods had cross-browser issues and stuff like date.js had not been updated in quite a while.
You also don't need a datePicker on the page. You can just call something similar to the example given in the docs:
$.parseDate('yy-mm-dd', '2007-01-26');
I just discovered that the 1.2.3 version of Steven Levithan's date.format.js does just what I want. It allows you to supply a format string for a JavaScript date and will convert from local time to UTC. Here's the code I'm using now:
// JavaScript dates don't like hyphens!
var rectifiedDateText = dateText.replace(/-/g, "/");
var d = new Date(rectifiedDateText);
// Using a predefined mask from date.format.js.
var convertedDate = dateFormat(d, 'isoUtcDateTime');
Using moment.js UTC method;
const moment = require('moment');
const utc = moment.utc(new Date(string));
This function works beautifully for me.
function ParseDateForSave(dateValue) {
// create a new date object
var newDate = new Date(parseInt(dateValue.substr(6)));
// return the UTC version of the date
return newDate.toISOString();
}
This method will give you : 2017-08-04T11:15:00.000+04:30 and you can ignore zone variable to simply get 2017-08-04T11:15:00.000.
function getLocalIsoDateTime(dtString) {
if(dtString == "")
return "";
var offset = new Date().getTimezoneOffset();
var localISOTime = (new Date(new Date(dtString) - offset * 60000 /*offset in milliseconds*/)).toISOString().slice(0,-1);
//Next two lines can be removed if zone isn't needed.
var absO = Math.abs(offset);
var zone = (offset < 0 ? "+" : "-") + ("00" + Math.floor(absO / 60)).slice(-2) + ":" + ("00" + (absO % 60)).slice(-2);
return localISOTime + zone;
}
If you need Date Object
Passing only date string Date assumes time to be 00:00 shifted by time zone:
new Date('2019-03-11')
Sun Mar 10 2019 18:00:00 GMT-0600 (Central Standard Time)
If you add current hours and minutes you get proper date:
new Date('2019-03-11 ' + new Date().getHours() + ':' + new Date().getMinutes())
Mon Mar 11 2019 04:36:00 GMT-0600 (Central Standard Time)
The getTimezoneOffset() method returns the time zone difference, in
minutes, from current locale (host system settings) to UTC.
Source: MDN web docs
This means that the offset is positive if the local timezone is behind UTC, and negative if it is ahead. For example, for time zone UTC+02:00, -120 will be returned.
let d = new Date();
console.log(d);
d.setTime(d.getTime() + (d.getTimezoneOffset() * 60000));
console.log(d);
NOTE: This will shift the date object time to UTC±00:00 and not convert its timezone so the date object timezone will still the same but the value will be in UTC±00:00.
This is what I have done in the past:
var utcDateString = new Date(new Date().toUTCString()).toISOString();
For other people whos goal is to get it as a "Date Object" and not as a string, and you only want to display the date/time without the TZ (probably hardcoded), what you can do is:
const now = new Date();
const year = now.getUTCFullYear();
const month = now.getUTCMonth();
const day = now.getUTCDate();
const hour = now.getUTCHours();
const tomorrowUTC= new Date();
tomorrowUTC.setDate(day + 1); // +1 because my logic is to get "tomorrow"
tomorrowUTC.setYear(year);
tomorrowUTC.setMonth(month);
tomorrowUTC.Hours(hour);
// then use the tomorrowUTC for to display/format it
// tomorrowUTC is a "Date" and not a string.
You can then do stuff like:
We will delete your account at ${format(tomorrowUTC, 'EEEE do MMMM hh:mmaaa')} UTC
(format is a date-fns function, you can use other lib if you want);
This is kinda "hacky" as this is still using your local timezone, but if you just wanna display the date and not the timezone, then this works.
If your date has the timezone on it you can use date-fns-tz:
import { zonedTimeToUtc } from 'date-fns-tz';
const dateBrazil = new Date() // I'm in Brazil, you should have or get the user timezone.
const dateUtc = zonedTimeToUtc(dateBrazil, 'America/Sao_Paulo')
Looking at your question its clear that you just want to send the date range to your backend for further post processing.
I am assuming you are conforming to the standard data guidelines which expect the data to be in a particular format. For example, I use ODATA which is a RESTfull API which expects date time objects to be in the format:-
YYYY-MM-DDT00:00:00.
That can be easily achieved via the snippet posted below(Please change the format as per your requirement).
var mydate;//assuming this is my date object which I want to expose
var UTCDateStr = mydate.getUTCFullYear() + "-" + mydate.getUTCMonth() + "-" + mydate.getUTCDate() + "T00:00:00";
If on the other hand, you are in my situation wherein you have received a date from your backend, and the browser converts that to your local date. You on the other hand are interested in the UTC date then you can perform the following:-
var mydate;//assuming this is my date object which I want to expose
var UTCDate = new Date(mydate);/*create a copy of your date object. Only needed if you for some reason need the original local date*/
UTCDate.setTime(UTCDate.getTime() + UTCDate.getTimezoneOffset() * 60 * 1000);
The code snippet above basically adds/subtracts the time added/subtracted by the browser based on the timezone.
For example if I am in EST(GMT-5) and my Service returns a date time object = Wed Aug 17 2016 00:00:00 GMT-0500
my browser automatically subtracts the timezone offset(5hrs) to get my local time. So if I try to fetch the time I get Wed Aug 16 2016 19:00:00 GMT-0500. This causes a lot of problems. There are a lot of libraries out there which will definitely make this easier but I wanted to share the pure JS approach.
For more info please have a look at: http://praveenlobo.com/blog/how-to-convert-javascript-local-date-to-utc-and-utc-to-local-date/ where in I got my inspiration.
Hope this helps!
var userdate = new Date("2009-1-1T8:00:00Z");
var timezone = userdate.getTimezoneOffset();
var serverdate = new Date(userdate.setMinutes(userdate.getMinutes()+parseInt(timezone)));
This will give you the proper UTC Date and Time.
It's because the getTimezoneOffset() will give you the timezone difference in minutes.
I recommend you that not to use toISOString() because the output will be in the string Hence in future you will not able to manipulate the date
Using moment package, you can easily convert a date string of UTC to a new Date object:
const moment = require('moment');
let b = new Date(moment.utc('2014-02-20 00:00:00.000000'));
let utc = b.toUTCString();
b.getTime();
This specially helps when your server do not support timezone and you want to store UTC date always in server and get it back as a new Date object. Above code worked for my requirement of similar issue that this thread is for. Sharing here so that it can help others. I do not see exactly above solution in any answer. Thanks.
I know this question is old, but was looking at this same issue, and one option would be to send date.valueOf() to the server instead. the valueOf() function of the javascript Date sends the number of milliseconds since midnight January 1, 1970 UTC.
valueOf()
You can use the following method to convert any js date to UTC:
let date = new Date(YOUR_DATE).toISOString()
// It would give the date in format "2020-06-16T12:30:00.000Z" where Part before T is date in YYYY-MM-DD format, part after T is time in format HH:MM:SS and Z stands for UTC - Zero hour offset
By far the best way I found to get the GMT time is first get your local date time. Then convert in to GMT String. Then use the string to build new time by removing the timezone.
let dtLocal = new Date()
let dt = new Date(dtLocal.toISOString().split('Z')[0])
Note: - it will create the new datetime in GMT. But it will be local date time as timezone will be attached to it.
Extension function:
if (!Date.prototype.toUTC){
Date.prototype.toUTC = function(){
var utcOffset = new Date().getTimezoneOffset();
var utcNow = new Date().addMinutes(utcOffset);
return utcNow;
};
}
Usage:
new Date().toUTC();

Same date in all timezones

I have a problem showing the same date in all timezones.
Users input is for example 01-01-2002 and I store it like a date with Eureope/Berlin timezone
parseFromTimeZone(String(birthDate), { timeZone: 'Europe/Berlin' })
and the result of parseFromTimeZone is this string '2001-12-31T23:00:00.000Z'. String date counts with timezone in Berlin that is why it is shifted for one hour.
And I need to get from '2001-12-31T23:00:00.000Z' this 01-01-2002 in all timezones.
I using formatISO(new Date(date), { representation: 'date' })) this returns 01-01-2002 when my timezone is Europe/Prague or Europe/Berlin
but when I change the timezone to America/Tijuana then formatISO returns 2001-12-31 and that is wrong I need to have the same date as is in Europe/Berlin always! Bud for Asia/Tokyo this function returns 01-01-2002 that is right ...
Some ideas? I have tried a lot of solutions but none works for all timezones...
I am using "date-fns": "^2.15.0", "date-fns-timezone": "^0.1.4"
Try this function with an ISO_8601 date, then change the timezone in your computer's settings and try again with the new timezone. It should print the same date on your web page for both time zones.
getDateFromISO(iso_string: string): string | Date {
if (!iso_string)
return null;
const isIsoDate = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/.test(iso_string); // check if string is in format 2022-01-01T00:00:00.000Z
const isDateTimeWithoutZone = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(iso_string); // check if string is in format 2022-01-01T00:00:00
const isDateYMD = /\d{4}-\d{2}-\d{2}/.test(iso_string); // check if string is in format 2022-01-01
if (!isIsoDate && isDateTimeWithoutZone)
iso_string += '.000Z';
else if (!isIsoDate && isDateYMD)
iso_string += 'T00:00:00.000Z';
else if (isIsoDate)
iso_string = iso_string;
else
return iso_string;
const dateFromServer = new Date(iso_string);
const localOffset = new Date().getTimezoneOffset(); // in minutes
const localOffsetMillis = 60 * 1000 * localOffset;
const localDate = new Date(dateFromServer.getTime() + localOffsetMillis);
return localDate;
}
The Date object, despite its name, is does not represent a "date". It represents a timestamp. All that it stores internally is the number of milliseconds since the Unix epoch (which is UTC based). It outputs values based on either UTC or the local time zone of the machine where its running, depending on the function being called.
Thus, if you construct a Date object from a date-only value, you're really taking "the time at midnight" from that time zone and adjusting it to UTC. This is demonstrated by your example of 2002-01-01 in Europe/Berlin. Your treating that as 2002-01-01T00:00:00.000+01:00, which indeed has a UTC equivalent of 2001-12-31T23:00:00.000Z, and thus doesn't carry the same year, month, and day elements as the intended time zone.
You really only have two options to deal with date-only values if you want to prevent them from shifting:
Your first option is to use the Date object, but treat the input as UTC and only use the UTC-based functions. For example:
var dt = new Date(Date.UTC(2002, 0, 1)); // "2002-01-01T00:00:00.000Z"
var y = dt.getUTCFullYear(); // 2002
var m = dt.getUTCMonth() + 1; // 1
var d = dt.getUTCDate(); // 1
var dtString = d.toISOString().substring(0, 10) // "2002-01-01"
If you need to parse a date string, be aware that current ECMAScript spec treats date-only values as UTC (which is what you want), but in the past such behavior was undefined. Thus some browsers might create a local-time result from new Date('2002-01-01'). You may want to explicitly add the time and Z, as in new Date('2002-01-01' + 'T00:00:00.000Z') to be on the safe side.
If you intend to use date-fns, be careful - the parseISO and formatISO functions use local time, not UTC.
The second option is to not use the Date object. Keep the dates in their string form (in ISO 8601 yyyy-mm-dd format), or keep them in a different object of either your own construction or from a library.
The ECMAScript TC39 Temporal proposal is intended to fix such deficiencies in JavaScript. In particular, the Temporal.Date object (preliminary name) will be able to be used for date-only values without having the shifting problem you and so many others have encountered. The proposal is currently in Stage 2 of the ECMAScript process, so it's not available to use today, but this problem will be solved eventually!

Get GMT time for date and time

I have a string in GMT "2017-01-17 00:00:00.000" and I want to get time and date differently (the string does not have to be in that format).
I tried:
var datetime = new Date(calEvent.start);
var date = datetime.toLocaleDateString(); //output: 1/16/2017
var time = datetime.toLocaleTimeString(); //output: 4:00:00 PM
but the output for date and time I want should be in GMT timezone. Anyone know how to do that without using substring for string?
Thanks
The string "2017-01-17 00:00:00.000" is not consistent with the subset of ISO 8601 specified in ECMA-262 and will not be parsed correctly in some browsers. As it is, it will be treated as local if parsed at all.
You can modify the string by adding a "T" between the date and time and a trailing "Z" for UTC, then let the Date constructor parse it, e.g.
var s = '2017-01-17 00:00:00.000';
var d = new Date(s.replace(' ', 'T') + 'Z');
console.log(d);
Which will work in most modern browsers, however it will fail in older browsers like IE. You can also write a small function to parse the strting as UTC:
function parseAsUTC(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0], b[1] - 1, b[2], b[3], b[4], b[5], b[6]));
}
console.log(parseAsUTC('2017-01-17 00:00:00.000'));
You can also use one of the various libraries available, however if all you need it to parse one particular format, then that's not necessary.
NOTE:
It's generally not recommended to parse strings with the Date constructor (or Date.parse) as they are largely implementation dependent, however the ISO 8601 extended format is now fairly well supported and is specified in ECMA-262.
The time zone must be specified with upper case "Z". Firefox (at least) will generate an invalid date if "z" is used.

Issue with javascript date object

I am facing a weird problem while initializes javascript date object,no matter what I initialize to it shows the date as 1 JAN 1970 05:30;
this is the way I try to initialize
var d=new date(27-02-1989);
alerting 'd' shows 1 JAN 1970.....,also sometimes it takes a date passed from the database but in the format as mm/dd/yyyy not in the format I want i.e dd/mm/yyyy
This problem has suddenly popped-up, as everything was working smooth couple of days ago,but today after opening the project (after 2 days) this issue is irritating me
I see you've accepted an answer, but it isn't the best you can do. There is no one format that is parsed correctly by all browsers in common use, the accepted answer will fail in IE 8 at least.
The only safe way to convert a string to a date is to parse it, e.g.
var s = '27-02-1989';
var bits = s.split('-');
var date = new Date(bits[2], --bits[1], bits[0]);
// Transform your european date in RFC compliant date (american)
var date = '27-02-1989'.split('-').reverse().join('-');
// And this works
var d = new Date( date );
Proof:
You're doing an initialization with a negative integer value (27-02-1989 == -1964). The Date object's constructor takes arguments listed here.
If you want to pass strings, they need to be in an RFC2822-compliant format (see here).
according to here you can try:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day [, hour, minute, second, millisecond ])
so for your case use (edit: You need to remember that months are zero based)
var d = new Date(1989,01,27);
pleas notice - use Date (capital D)
First of all
var d=new date(27-02-1989);
is totaly wrong expression in javascript, moreover even if we rewrites it more correctly:
var d=new Date('27-02-1989');
there is no way to parse this date string natively in js.
Here solutions you can try:
transform string to ISO8601: YYYY-mm-dd, this can be parsed by most modern broswers, or you can use many js libraries for polyfill
split string string by '-' and then use Date constructor function new Date(year, month-1, day)
split string and use setDate, setMonth, setYear method on new Date() object
Note that in last two methods you need to deduct 1 from month value, because month is zero-based (0 stands for January, 11 for December)

Invalid date in safari

alert(new Date('2010-11-29'));
chrome, ff doesn't have problems with this, but safari cries "invalid date". Why ?
edit : ok, as per the comments below, I used string parsing and tried this :
alert(new Date('11-29-2010')); //doesn't work in safari
alert(new Date('29-11-2010')); //doesn't work in safari
alert(new Date('2010-29-11')); //doesn't work in safari
edit Mar 22 2018 : Seems like people are still landing here - Today, I would use moment or date-fns and be done with it. Date-fns is very much pain free and light as well.
For me implementing a new library just because Safari cannot do it correctly is too much and a regex is overkill.
Here is the oneliner:
console.log (new Date('2011-04-12'.replace(/-/g, "/")));
The pattern yyyy-MM-dd isn't an officially supported format for Date constructor. Firefox seems to support it, but don't count on other browsers doing the same.
Here are some supported strings:
MM-dd-yyyy
yyyy/MM/dd
MM/dd/yyyy
MMMM dd, yyyy
MMM dd, yyyy
DateJS seems like a good library for parsing non standard date formats.
Edit: just checked ECMA-262 standard. Quoting from section 15.9.1.15:
Date Time String Format
ECMAScript defines a string
interchange format for date-times
based upon a simplification of the ISO
8601 Extended Format. The format is
as follows: YYYY-MM-DDTHH:mm:ss.sssZ
Where the fields are as follows:
YYYY is the decimal digits of the year in the Gregorian calendar.
"-" (hyphon) appears literally twice in the string.
MM is the month of the year from 01 (January) to 12 (December).
DD is the day of the month from 01 to 31.
"T" appears literally in the string, to indicate the beginning of
the time element.
HH is the number of complete hours that have passed since midnight as two
decimal digits.
":" (colon) appears literally twice in the string.
mm is the number of complete minutes since the start of the hour as
two decimal digits.
ss is the number of complete seconds since the start of the minute
as two decimal digits.
"." (dot) appears literally in the string.
sss is the number of complete milliseconds since the start of the
second as three decimal digits. Both
the "." and the milliseconds field may
be omitted.
Z is the time zone offset specified as "Z" (for UTC) or either "+" or "-"
followed by a time expression hh:mm
This format includes date-only forms:
YYYY
YYYY-MM
YYYY-MM-DD
It also includes time-only forms with
an optional time zone offset appended:
THH:mm
THH:mm:ss
THH:mm:ss.sss
Also included are "date-times" which
may be any combination of the above.
So, it seems that YYYY-MM-DD is included in the standard, but for some reason, Safari doesn't support it.
Update: after looking at datejs documentation, using it, your problem should be solved using code like this:
var myDate1 = Date.parseExact("29-11-2010", "dd-MM-yyyy");
var myDate2 = Date.parseExact("11-29-2010", "MM-dd-yyyy");
var myDate3 = Date.parseExact("2010-11-29", "yyyy-MM-dd");
var myDate4 = Date.parseExact("2010-29-11", "yyyy-dd-MM");
I was facing a similar issue. Date.Parse("DATESTRING") was working on Chrome (Version 59.0.3071.115 ) but not of Safari (Version 10.1.1 (11603.2.5) )
Safari:
Date.parse("2017-01-22 11:57:00")
NaN
Chrome:
Date.parse("2017-01-22 11:57:00")
1485115020000
The solution that worked for me was replacing the space in the dateString with "T". ( example : dateString.replace(/ /g,"T") )
Safari:
Date.parse("2017-01-22T11:57:00")
1485086220000
Chrome:
Date.parse("2017-01-22T11:57:00")
1485115020000
Note that the response from Safari browser is 8hrs (28800000ms) less than the response seen in Chrome browser because Safari returned the response in local TZ (which is 8hrs behind UTC)
To get both the times in same TZ
Safari:
Date.parse("2017-01-22T11:57:00Z")
1485086220000
Chrome:
Date.parse("2017-01-22T11:57:00Z")
1485086220000
I use moment to solve the problem.
For example
var startDate = moment('2015-07-06 08:00', 'YYYY-MM-DD HH:mm').toDate();
To have a solution working on most browsers, you should create your date-object with this format
(year, month, date, hours, minutes, seconds, ms)
e.g.:
dateObj = new Date(2014, 6, 25); //UTC time / Months are mapped from 0 to 11
alert(dateObj.getTime()); //gives back timestamp in ms
works fine with IE, FF, Chrome and Safari. Even older versions.
IE Dev Center: Date Object (JavaScript)
Mozilla Dev Network: Date
convert string to Date fromat (you have to know server timezone)
new Date('2015-06-16 11:00:00'.replace(/\s+/g, 'T').concat('.000+08:00')).getTime()
where +08:00 = timeZone from server
I had the same issue.Then I used moment.Js.Problem has vanished.
When creating a moment from a string, we first check if the string
matches known ISO 8601 formats, then fall back to new Date(string) if
a known format is not found.
Warning: Browser support for parsing strings is inconsistent. Because
there is no specification on which formats should be supported, what
works in some browsers will not work in other browsers.
For consistent results parsing anything other than ISO 8601 strings,
you should use String + Format.
e.g.
var date= moment(String);
For people using date-fns we can parseISO date and use it to format
Invalid
import _format from 'date-fns/format';
export function formatDate(date: string, format: string): string {
return _format(new Date(date), format);
}
This function on safari throw error with Invalid date.
Solution
To fix it we should use:
import _format from 'date-fns/format';
import _parseISO from 'date-fns/parseISO';
export function formatDate(date: string, format: string): string {
return _format(_parseISO(date), format);
}
Though you might hope that browsers would support ISO 8601 (or date-only subsets thereof), this is not the case. All browsers that I know of (at least in the US/English locales I use) are able to parse the horrible US MM/DD/YYYY format.
If you already have the parts of the date, you might instead want to try using Date.UTC(). If you don't, but you must use the YYYY-MM-DD format, I suggest using a regular expression to parse the pieces you know and then pass them to Date.UTC().
How about hijack Date with fix-date? No dependencies, min + gzip = 280 B
I am also facing the same problem in Safari Browser
var date = new Date("2011-02-07");
console.log(date) // IE you get ‘NaN’ returned and in Safari you get ‘Invalid Date’
Here the solution:
var d = new Date(2011, 01, 07); // yyyy, mm-1, dd
var d = new Date(2011, 01, 07, 11, 05, 00); // yyyy, mm-1, dd, hh, mm, ss
var d = new Date("02/07/2011"); // "mm/dd/yyyy"
var d = new Date("02/07/2011 11:05:00"); // "mm/dd/yyyy hh:mm:ss"
var d = new Date(1297076700000); // milliseconds
var d = new Date("Mon Feb 07 2011 11:05:00 GMT"); // ""Day Mon dd yyyy hh:mm:ss GMT/UTC
Use the below format, it would work on all the browsers
var year = 2016;
var month = 02; // month varies from 0-11 (Jan-Dec)
var day = 23;
month = month<10?"0"+month:month; // to ensure YYYY-MM-DD format
day = day<10?"0"+day:day;
dateObj = new Date(year+"-"+month+"-"+day);
alert(dateObj);
//Your output would look like this "Wed Mar 23 2016 00:00:00 GMT+0530 (IST)"
//Note this would be in the current timezone in this case denoted by IST, to convert to UTC timezone you can include
alert(dateObj.toUTCSting);
//Your output now would like this "Tue, 22 Mar 2016 18:30:00 GMT"
Note that now the dateObj shows the time in GMT format, also note that the date and time have been changed correspondingly.
The "toUTCSting" function retrieves the corresponding time at the Greenwich meridian. This it accomplishes by establishing the time difference between your current timezone to the Greenwich Meridian timezone.
In the above case the time before conversion was 00:00 hours and minutes on the 23rd of March in the year 2016. And after conversion from GMT+0530 (IST) hours to GMT (it basically subtracts 5.30 hours from the given timestamp in this case) the time reflects 18.30 hours on the 22nd of March in the year 2016 (exactly 5.30 hours behind the first time).
Further to convert any date object to timestamp you can use
alert(dateObj.getTime());
//output would look something similar to this "1458671400000"
This would give you the unique timestamp of the time
Best way to do it is by using the following format:
new Date(year, month, day, hours, minutes, seconds, milliseconds)
var d = new Date(2018, 11, 24, 10, 33, 30, 0);
This is supported in all browsers and will not give you any issues.
Please note that the months are written from 0 to 11.
For me the issue was I forgot to add 0 before the single digit month or day in YYYY-MM-DD format.
What I was parsing: 2021-11-5
What it should be: 2021-11-05
So, I wrote a little utility which converts YYYY-M-D to YYYY-MM-DD i.e. 2021-1-1 to 2021-01-01:
const date = "2021-1-1"
const YYYY = date.split("-")[0];
//convert M->MM i.e. 2->02
const MM =
date.split("-")[1].length == 1
? "0" + date.split("-")[1]
: date.split("-")[1];
//convert D->DD i.e. 2->02
const DD =
date.split("-")[2].length == 1
? "0" + date.split("-")[2]
: date.split("-")[2];
// YYYY-MM-DD
const properDateString = `${YYYY + "-" + MM + "-" + DD}`;
const dateObj = new Date(properDateString);
As #nizantz previously mentioned, using Date.parse() wasn't working for me in Safari. After a bit of research, I learned that the lastDateModified property for the File object has been deprecated, and is no longer supported by Safari. Using the lastModified property of the File object resolved my issues. Sure dislike it when bad info is found online.
Thanks to all who contributed to this post that assisted me in going down the path I needed to learn about my issue. Had it not been for this info, I never would have probably figured out my root issue. Maybe this will help someone else in my similar situation.
Arriving late to the party but in our case we were getting this issue in Safari & iOS when using ES6 back tick instead of String() to type cast
This was giving 'invalid date' error
const dateString = '2011-11-18';
const dateObj = new Date(`${dateString}`);
But this works
const dateObj = new Date(String(dateString));
In my case, it wasn't the formatting, it was because in my backend Node.js Model, I was defining the database variable as a String instead of a Date.
My backend Node Database Model said:
starttime:{
type: String,
}
instead of the correct:
starttime:{
type: Date,
}
The same problem facing in Safari and it was solved by inserting this in web page
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en"></script>
Hope it will work also your case too
Thanks
This will not work alert(new Date('2010-11-29')); safari have some weird/strict way of processing date format alert(new Date(String('2010-11-29'))); try like this.
(Or)
Using Moment js will solve the issue though, After ios 14 the safari gets even weird
Try this alert(moment(String("2015-12-31 00:00:00")));
Moment JS
use the format 'mm/dd/yyyy'. For example :- new Date('02/28/2015'). It works well in all browsers.
This is not the best solution, although I simply catch the error and send back current date. I personally feel like not solving Safari issues, if users want to use a sh*t non-standards compliant browser - they have to live with quirks.
function safeDate(dateString = "") {
let date = new Date();
try {
if (Date.parse(dateString)) {
date = new Date(Date.parse(dateString))
}
} catch (error) {
// do nothing.
}
return date;
}
I'd suggest having your backend send ISO dates.

Categories

Resources