NOTE: This is not a duplicate. I already refer to the other question mentioned. I'm pointing out that the advice given there doesn't work.
I'm trying to create a JavaScript date representing the January 1st 0001 (i.e. the start of year 1 AD).
At first I naively thought that this would do it:
const date = new Date(1, 0, 1);
...but that doesn't work. That actually yields January 1st 1901.
This behaviour (which is documented) is discussed in this question.
The proposed solution is to construct the date and then use setUTCFullYear to set the actual year required, like this:
const date = new Date(1, 0, 1);
date.setUTCFullYear(1);
Well, I tried doing that, and the date I end up with is:
Sun Dec 31 0000 23:58:45 GMT-0001 (Greenwich Mean Time)
See this StackBlitz for a "demo".
I don't understand that behaviour at all. Where did that extra 1 minute and 15 seconds go?
And... how can I actually get the date I need, other than by resorting to Date.parse()?
I'll post an answer since everyone prefers just to comment :-)
It turns out that the date I created was "correct", but that it was being displayed in a (erm...) "surprising" way.
So:
const date = new Date(Date.UTC(1, 0, 1));
console.log(date);
1901-01-01T00:00:00.000Z
date.setUTCFullYear(1);
console.log(date);
0001-01-01T00:00:00.000Z
That's what I wanted, but what I was seeing was:
console.log(date.toString());
Sun Dec 31 0000 23:58:45 GMT-0001 (Greenwich Mean Time)
(I still think that result is weird). I would have been better to do:
console.log(date.toUTCString());
Mon, 01 Jan 0001 00:00:00 GMT
Thanks everyone!
Related
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 6 years ago.
I feel like I am missing something here.
The Date.getDay() method is supposed to return a value from 0-6. 0 for Sunday and 6 for Saturday.
Now I have two dates, both are 'Sunday' which should return 0.
new Date('1990-11-11').getDay() // returns 6
new Date('2016-1-3').getDay() // returns 0
What is causing the discrepancy? I dare to question the validity of the .getDay() method, but I can't figure out what is going on.
EDIT
> new Date('1990-11-11')
Sat Nov 10 1990 17:00:00 GMT-0700 (MST)
> new Date('2016-01-03')
Sat Jan 02 2016 17:00:00 GMT-0700 (MST)
> new Date('2016-1-3') // they say this format is wrong, but it returns the right date
Sun Jan 03 2016 00:00:00 GMT-0700 (MST)
I don't understand what is going on. January 3rd is Sunday and November 11th 1990 is Sunday. Why is it saying Saturday?
The one that is wrong is the one that returns Sunday, and that must be because the format is incorrect. 1990-11-11 is interpreted as 00:00:00 on midnight of the 11th, UTC, which is 5pm on Saturday the 10th in your time zone.
If you use getUTCDay(), you should get 0 for both dates.
new Date('1990-11-11').getUTCDay() // returns 0
new Date('2016-01-03').getUTCDay() // returns 0
Certainly, your claim that 1990-11-11 is Sunday is true but you have to understand that JavaScript Date object:
Handles time as well as date
Is time zone aware
Is poorly designed and rather counter-intuitive
Your own tests illustrate this:
new Date('1990-11-11').getDay() // returns 6
> new Date('1990-11-11')
Sat Nov 10 1990 17:00:00 GMT-0700 (MST)
What happens is that constructor assumes local time or UTC depending on the syntax used:
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: parsing of date strings with the Date constructor (and
Date.parse, they are equivalent) is strongly discouraged due to
browser differences and inconsistencies. Support for RFC 2822 format
strings is by convention only. Support for ISO 8601 formats differs in
that date-only strings (e.g. "1970-01-01") are treated as UTC, not
local.
... and your syntax makes it as UTC. But many others methods assume local time:
The getDay() method returns the day of the week for the specified date
according to local time, where 0 represents Sunday.
getDay returns day index (from 0 to 6), where 0 is Sunday.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay
Return value:
An integer number corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.
Update:
new Date constructor returns different time values for those dates.
new Date('2016-1-3')
==> Sun Jan 03 2016 00:00:00 GMT+0100 (CET)
new Date('1990-11-11')
==> Sun Nov 11 1990 01:00:00 GMT+0100 (CET)
And for some reason, the first one gets interpreted as Saturday on your machine.
Sorry for not being able to help out more
Update2:
Using two digits for month/day should standardize the results.
Example:
(new Date('2016-01-03')).getDay() ==> 0
Is there a way to get the Sunday thru Saturday dates of the week based on week number?
For example the current week number is 32, so I would want an array (or some return type) as such:
["Sunday, July 3rd, 2016", "Monday, July 4th, 2016".... etc ]
The documentation here states that use can use the syntax below, however this seems to simply gives me the current day (unless I'm reading the output wrong).
moment().weeks(32)
Output: Fri Aug 05 2016 11:19:39 GMT-0400
Would suggest to not go for additional libraries. Once you get first day for given week number using moment().weeks(32), write a simple method to return next seven days using moment().add() method.
This question already has answers here:
Javascript date parsing bug - fails for dates in June (??)
(5 answers)
Closed 8 years ago.
I'm getting some really strange behaviour with Javascript date objects.
var t = new Date();
t.setUTCFullYear(2014);
t.setUTCMonth(10);
t.setUTCDate(20);
console.log(t);
This returns:
Date {Sat Dec 20 2014 10:26:23 GMT-0800 (PST)}
Whereas if you use t.setMonth(10), you correctly get November. Am I doing something wrong?
This will work as expected tomorrow.
Today (October 31st), t is initialized with its day as 31. When you set the month to November, you're setting "November 31st", which is corrected to December 1st.
Then you set the date to 20, but the month has already changed. Set the date first, or better yet, use the two-argument verson of setUTCMonth():
t.setUTCMonth(10, 20);
Maybe I'm missing something (EDIT: I was, Paul's answer covers it), but you're right. However, this works:
var t = new Date();
t.setUTCFullYear(2014);
t.setUTCMonth(10, 20); // Set day here instead
console.log(t); // Thu Nov 20 2014 12:40:42 GMT-0600 (Central Standard Time)
It also works if you switch the order of the set statements:
var t = new Date();
t.setUTCFullYear(2014);
t.setUTCDate(20);
t.setUTCMonth(10);
The problem is a mixture of particular dates and the order of setting individual parts of the date. If you step through what's happening it becomes clearer:
New date is initialised as today: Oct 31, 2014
Setting the year to 2014: no effect
Setting the month to November: Nov 31, 2014 is interpreted as Dec 1, 2014
Setting the date to 20: Dec 20, 2014
I have a js timestamp of Tue Sep 30 2014 12:02:50 GMT-0400 (EDT)
with .getTime() I got 1412092970.768
for most cases, its a today's specific time stamp. I wonder, if I could always ONLY pick out the day month and year and hour, min, day will be always stay with 0.
So for our situation, it should become Tue Sep 30 2014 00:00:00 GMT-0400 (EDT).
I wonder what kind of conversion should I be doing? Because seem convert to unix timestamp with getTime() will result in unknown way of calculation... and I can not really find a way to set time like I would do in PHP.
Any fix for this situation?
Thanks
You can create a date object and then zero-out any components you don't need, or create one with the components you specified, e.g.
foo = new Date();
foo.setHour(0);
foo.setMinute(0);
or something more like
foo = new Date(); // "now"
bar = new Date(foo.getYear(), foo.getMonth(), foo.getDate(), 0 , 0, 0, 0);
// create new date with just year/month/day value, and time zeroed-out.
The constructor's args are detailed here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
An other option is to send epoch to PHP:
JS:
long epoch = System.currentTimeMillis()/1000;
PHP:
$dt = new DateTime("#$epoch");
$dt->format('Y'); //year
I have an issue -
The javascript Date("mm-dd-yyyy") constructor doesn't work for FF. It works fine for IE.
IE : new Date("04-02-2008") => "Wed Apr 2 00:00:00 EDT 2008"
FF2 : new Date("04-02-2008") => Invalid Date
So lets try another constructor. Trying this constructor Date("yyyy", "mm", "dd")
IE : new Date("2008", "04", "02"); => "Fri May 2 00:00:00 EDT 2008"
FF : new Date("2008", "04", "02"); => "Fri May 2 00:00:00 EDT 2008"
IE : new Date("2008", "03", "02"); => "Wed Apr 2 00:00:00 EDT 2008"
FF : new Date("2008", "03", "02"); => "Wed Apr 2 00:00:00 EDT 2008"
So the Date("yyyy", "mm", "dd") constructor uses an index of 0 to represent January.
Has anyone dealt with this?
There must be a better way than subtracting 1 from the months.
It is the definition of the Date object to use values 0-11 for the month field.
I believe that the constructor using a String is system-dependent (not to mention locale/timezone dependent) so you are probably better off using the constructor where you specify year/month/day as seperate parameters.
BTW, in Firefox,
new Date("04/02/2008");
works fine for me - it will interpret slashes, but not hyphens. I think this proves my point that using a String to construct a Date object is problemsome. Use explicit values for month/day/year instead:
new Date(2008, 3, 2);
nice trick indeed, which i just found out the hard way (by thinking thru it).
But i used a more natural date string with hyphen :-)
var myDateArray = "2008-03-02".split("-");
var theDate = new Date(myDateArray[0],myDateArray[1]-1,myDateArray[2]);
alert(theDate);
Using
var theDate = new Date(myDate[0],myDate[1]-1,myDate[2]);
Is fine, but it shows some strange behaviors when month and day values are erroneous.
Try casting a date where both myDate[1]-1 and myDate[2] have values of 55. Javascript still returns a date, though the input is obviously not correct.
I would have preferred javascript to return an error in such a case.
#Frank: you are right. When you need to validate date,
var theDate = new Date(myDate[0],myDate[1]-1,myDate[2]);
will not work.
What happens is that it keeps on adding the extra parameter. For example:
new Date("2012", "11", "57") // Date {Sat Jan 26 2013 00:00:00 GMT+0530 (IST)}
Date object takes the extra days (57-31=26) and adds it to the date we created.
Or if we try constructing a date object with:
new Date("2012", "11", "57", "57") //Date {Mon Jan 28 2013 09:00:00 GMT+0530 (IST)}
an extra 2 days and 9 hours (57=24+24+9) are added.
You're quite right, month is indicated as an index, so January is month number 0 and December is month number 11 ...
-- and there is no work-around as it is stated clearly in the ECMA-script-definition, though simple tricks commonly will work:
var myDate = "2008,03,02".split(",");
var theDate = new Date(myDate[0],myDate[1]-1,myDate[2]);
alert(theDate);
Bold statement.
This might have your interest: JavaScript Pretty Date.