Issue with javascript date object - javascript

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)

Related

How do I get the next day's date in JS in YYYY-MM-DD format?

Seems like a simple question, but all the timezone ins and outs in JS are causing me a bunch of headaches.
Basically, if I have a date like the following:
2018-04-06
I want to be able to get the next day's date as such:
2018-04-07
I found the following snippet on SO for doing this (kind of):
var date = new Date('2018-04-06');
date.setDate(date + 1);
The problem is that I'm getting the date back with the adjusted timezone, and because I'm in the US ET timezone, it's giving me that date minus five hours, which is actually the same day as where I started.
I've been through countless SO posts trying to find an answer to this seemingly simple question, but for any given date, regardless of the timezone the user is in, how do I get the next day's date in YYYY-MM-DD format? Thank you.
Strings in the format YYYY-MM-DD are parsed as UTC so in this case, do everything in UTC (see Why does Date.parse give incorrect results? and How can I add 1 day to current date?).
The toISOString method will return the string in the required format, just trim the redundant time part, e.g.
let s = '2018-04-06';
let d = new Date(s);
d.setUTCDate(d.getUTCDate() + 1);
console.log(d.toISOString().substr(0,10));
Did you try with the UTC date?
var date = new Date('2018-04-06');
console.log(date.toUTCString());
date.setDate(date.getDate() + 1);
console.log(date.toUTCString());
As it was suggested by #chrisbyte, have your tried to use toUTCString method instead of toString() method ?
As a reminder , toString is the default used when you display the date object withim the console for example
I think the "problem" you're assuming is just an incomplete understanding how Date.toString() method behaves: this method seems to to return string representing a Date object but seems to use timezone as mentionned here (on the comment in 1st example)
Here my snippet to understand more:
const originalDate = new Date('2018-04-06');
// retrieving the original timestamp
const originalTimestamp = originalDate.valueOf()
// displaying the original date (non UTC / UTC)
console.log(`original date (timezone dependent): ${originalDate.toString()}`)
console.log(`original date (timezone independent): ${originalDate.toUTCString()}`)
// we add one more day
originalDate.setDate(originalDate.getDate() +1)
const dayAfterTimestamp = originalDate.valueOf()
// displaying the original date (non UTC / UTC)
console.log(`updated date (timezone dependent): ${originalDate.toString()}`)
console.log(`updated date (timezone independent): ${originalDate.toUTCString()}`)
// check the differences (in milliseconds)
console.log(`difference: ${(dayAfterTimestamp-originalTimestamp)}`)
// displaying the original format (timezone independent)
At last if you want to return the date string as a YYYY-MM-DD format you may have to implement it yourself :-/ , or use toLocaleFormat method but it isn't standardized.
The logic would be to add 24 hours in milliseconds to the current time. As an example:
var myDate = new Date();
var oneMoreDay = new Date();
oneMoreDay.setTime(myDate.getTime() + 86400000);
console.log(myDate.getDate());
console.log(oneMoreDay.getDate());
An additional day has been added to the oneMoreDay variable. In your specific example you just wanted to add one more day to the ORIGINAL variable, so i'd do something such as:
date.setTime(date.getTime() + 86400000);

Create a Date Object with the year only

I'm used to create Date objects by using the fourth syntax from MDN as new Date(year, month, day, hours, minutes, seconds, milliseconds); But lately I tried to set a Date object with only a year (as new Date(2017)) but as you could expect it was treated as a value and considered the year as a number of milliseconds.
Is there any way of still easily use the year as is without changing the syntax and expect a correctly set Date ?
Two solutions come to my mind:
(1) Set the year argument to 2017 and set the month argument to 0 when constructing the date:
let d = new Date(2017, 0);
console.log(d.toString());
The arguments will be treated as local time; month and day of month will be January 1; all time components will be set to 0.
(2) Specify "2017T00:00" as the first and only argument when constructing the date:
let d = new Date("2017T00:00");
console.log(d.toString());
According to current specs this is a valid format and browsers are supposed to treat it as local time. The behavior is same as that of previous example.
If you are passing a single parameter (number or string), then it is taken as per doc
value
Integer value representing the number of milliseconds since January 1,
1970 00:00:00 UTC, with leap seconds ignored (Unix Epoch; but consider
that most Unix time stamp functions count in seconds).
dateString
String value representing a date. The string should be in a format
recognized by the Date.parse() method (IETF-compliant RFC 2822
timestamps and also a version of ISO8601).
Also as per doc
If at least two arguments are supplied, missing arguments are either
set to 1 (if day is missing) or 0 for all others.
You can pass one more parameter as 0 or null (or the actual value you want to set)
new Date(2017,0);
Demo
var date = new Date(2017,0);
console.log( date );
You could pass null as second argument:
new Date(2017, null);
However, without knowing the details of how missing values are interpreted, what do you think happens now? Will the date be initialized with the current month, day, hour, etc? Or something different?
Better be explicit and pass all arguments, so that you know what the code is doing half a year later.
I have another suggestion. You can just create a regular date object and set it's year. So at least you know to expect what the rest of the Date object values are.
var year = "2014";
var date = new Date();
date.setFullYear(year);
// console.log(year) => Wed Dec 27 2014 16:25:28 GMT+0200
Further reading - Date.prototype.setFullYear()

Date(string) shows different date and time using toLocaleString

I want to turn the string 1822-01-01 00:00:00 into a date by:
var d= new Date("1822-01-01 00:00:00");
What I expect using d.toLocaleString() is 1.1.1822, 00:00:00, but what I get is 31.12.1821, 23:53:28.
See fiddle: https://jsfiddle.net/f1kLpfgd/
Javascript Date string constructing wrong date explains the wrong date with time zones. I have a different problem, as even minutes and seconds differ from my input. The solution using the new Date(1822, 0, 1, 0, 0, 0, 0) constructor does not work for me, as the result is 31.12.1821, 23:53:28.
Is it because the year is before 1901? But even 1899 works perfectly fine...
Update
For the formatting example custom VS toLocaleString, see updated fiddle: https://jsfiddle.net/f1kLpfgd/8/
If you don't want to use some library like date-fns , moment.js ...
To get the desired you could try like:
var dateString = "1822-01-01 00:00:00";
var d = new Date(dateString);
var formatted = d.getDate() +'.'+
(d.getMonth()+1) +'.'+
d.getFullYear() +', '+
dateString.substr(11);
console.log(formatted);
I want to turn the string 1822-01-01 00:00:00 into a date by:
var d= new Date("1822-01-01 00:00:00");
What I expect using d.toLocaleString() is 1.1.1822, 00:00:00, but what I get is 31.12.1821, 23:53:28.
Do not use the built-in parser for non-standard strings as whatever you get is implementation dependent and likely not what you expect in at least some hosts. In Safari, d will be an invalid date.
The format returned by toLocaleString is implementation dependent and varies between browsers. For me, new Date().toLocaleString() returns "9/21/2017, 9:48:49 AM", which is not consistent with the format typically used either in my locality or by users of the language I speak.
If you just want to reformat the string, see Reformat string containing date with Javascript.
If you want to know how to parse the string correctly, see Why does Date.parse
give incorrect results?
If you want to format a Date, see Where can I find documentation on formatting a date in JavaScript?

Date to epoch and vice versa - JavaScript

I need to convert date to Java epoch and then read it and convert back. Not sure what I'm doing wrong here?
var date = new Date('1/3/2013');
var timeStamp = date.getTime();
console.log(timeStamp);
var revertDate = new Date(timeStamp);
console.log(revertDate.getDate()+'/'+revertDate.getMonth()+'/'+revertDate.getFullYear());
The output is 3/0/2013 instad 1/3/2013?
fiddle link
You've got two problems here:
The Date constructor is assuming M/d/yyyy format - whereas you're logging d/M/yyyy format. Personally I'd suggest using an ISO-8601 format if at all possible: yyyy-MM-dd
You're not taking into account the fact that getMonth() returns a 0-based value
For the formatting side, you'd be better off using toISOString or something similar, rather than doing the formatting yourself.
(Note that looking at the documentation for the Date constructor it's not clear that the code you've got should work at all, as it's neither an RFC822 nor ISO-8601 format.)
Neither of the problems are to do with converting between Date and a numeric value. If you change your logging, you'll see that clearly:
var date = new Date('1/3/2013');
var timeStamp = date.getTime();
console.log(date);
var revertDate = new Date(timeStamp);
console.log(revertDate);
var date = new Date('1/3/2013');
The Date constructor is parsing this given string this way:
Month / Day / Year
So, in this case, Month is 1, Day is 3 and Year is 2013. What's going on there? Well that's quite simple. This Gregorian representation of a date(which is specifically Day / Month / Year ) isn't the one used by the Date constructor, so it will parse the 1(the month) as January, the 3 as the third day of the month(the third of Jan) and the year correctly, the 2013. Now, due to its 0-based indexing, the constructed Date object will return a month which is n-1 among the one provided. That's why you're getting 3/0/2013. It is the third day(3) of the month 0(which is January) of 2013. If you want to get your real date you have to do this:
var date = new Date('3/1/2013');
console.log(date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear());

Convert UTC date format into javascript format

How can I convert a date from:
Thu, 1 July 2011 22:30:00 to '2011-07-01T13:51:50.417' using javascript.
I get the UTC format when I do a new date.
IE causes me issues when I first create a date object as it shows: NaN
You could generate a new Date-Object and then get the different parts:
var today = new Date();
var year = today.getFullYear(); // Returns 2012
var month = today.getMonth()+1; // Returns the month (zero-based)
...
Then you can create a new string like you need it.
possible duplicate try search next time
stackoverflow question
Try http://www.datejs.com/. It is a JavaScript Date Library with an extended Date.parse method and a Date.parseExact method, which lets you specify a format string. See DateJS APIDocumentation.
and then you can manipulate it as you want
The d3.js library has some very solid routines for date conversions. See https://github.com/mbostock/d3/wiki/Time-Formatting#wiki-parse.

Categories

Resources