So I do not know if I doing something extremely wrong and stupid but here is my problem. Basically I am trying to learn the weekday value of the 1st day of the current month. To do this I created a Date object with current year and month but 1 as the date. But here is an interesting situation
var x = new Date()
console.log(x.getYear())
this prints out 115 to the console. I guess that is how they decided to represent 2000s. So if I do
var x = new Date();
var thismonth = new Date( x.getYear(), x.getMonth(), 1)
console.log(thismonth.getDay())
This prints out 5 when it should be printing out 0.Since 1st of Feb was a Sunday. On the other hand
var x = new Date(2015, 1 ,1 )
console.log(x.getDay())
prints out 0. So JS represents 2015, 115 but then can not handle its own representation ?
Is this caused by a problem in my browser or is this the general situation >
Thanks
You should use getFullYear() instead of getYear(). That will return what you are expecting.
Check out the API for more info on what each of the methods actually do.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Notice that the description of getYear() is: "Returns the year (usually 2-3 digits) in the specified date according to local time. Use getFullYear() instead." (emphasis added)
Related
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()
I am running this Javascript code on FireFox console:
> new Date(2015,01,29)
< Date 2015-03-01T03:00:00.000Z
I create a new date object with the date "2015-01-29" and the object instead saves the date "2015-03-01".
It also happens if I change the 'hour':
> new Date(2015,01,29,12)
< Date 2015-03-01T15:00:00.000Z
What's going on? I am completely lost on this.
How do I fix this 'bug'?
Thanks for helping!
Because the month-value starts with 0 (zero) new Date(2015,01,29) would be 29 of february which is not possible.
So for 2015-01-29 use 0 for the month parameter
new Date(2015,0,29)
MDN
new Date('2015,01,29') vs new Date(2015,01,29)
You are not using date input as string.
String format uses months as you would in real life: 01 - January.
Number format looks at months as indexes 0 - January.
I was trying to get the week day name using javascript getDay(). I know getDay() method returns the day of the week, like: 0 is sunday, 1 is monday etc.
var d=new Date("2014-05-26"); //this should return 1 so weekname monday.
alert(d.getDay()); // in india it returns correct value 1 fine.
But when i checked this code in USA it returns wrong number 0(sunday).
Can anybody tell me why is this happening?? I dont know where i'm doing wrong.
Thanks in advance.
Date constructor creates an instance using UTC, which differs from local time in both India and the US. You can check that by comparing
d.toLocaleString()
and
d.toUTCString()
So, what you probably need is
d.getUTCDay()
which returns the same result for all time zones.
You have two issues:
Passing a string to the Date constructor calls Date.parse, which is largely implementation dependent and differs between browsers even for the standardised parts.
ISO 8601 dates without a timezone are specified in ES5 to be treated as UTC, however some browsers treat them as local (and ES6 will change that so they should be treated as local).
So if you want consistent dates, write your own parser to turn the string into a date. Presumably you want strings without a time zone to be local, so:
function parseISODate(s) {
var b = s.split(/\D/);
var d = new Date();
d.setHours(0,0,0,0);
d.setFullYear(b[0], --b[1], b[2]);
return d.getFullYear() == b[0] && d.getDate() == b[2]? d : NaN;
}
The above function expects a date in ISO 8601 format without a timezone and converts it to a local date. If the date values are out of range (e.g. 2014-02-29) it returns NaN (per ES5). It also honours two digit years so that 0005-10-26 reuturns 26 October, 0005.
And:
parseISODate('2014-05-26').getDay() // 1
everywhere.
A simplistic version without the above (i.e. doesn't validate date values and turns years like 0005 into 1905) that can be used if you know the date string is always valid and you don't care about years 1 to 99 is:
function parseISODate(s) {
var b = s.split(/\D/);
return new Date(b[0], --b[1], b[2]);
}
try this,
var d=new Date("2014-05-26"); //this should return 1 so weekname monday.
var newDate = Date.UTC( d.getFullYear(), d.getMonth(), d.getDate());
alert(newDate.getDay()); // in india it returns correct value 1 fine.
you can produce same issue via changing your system date time zone change. set it to UTC -5/4/3 or UCT +5/4/3 and test this code
I was trying to convert date object into long format (may be in milliseconds format) as we do in java.
So to fulfill my need, after some trial and error, I found below way which works for me:
var date = new Date();
var longFormat = date*1; // dont know what it does internally
console.log(longFormat); // output was 1380625095292
To verify, I reverse it using new Date(longFormat); and it gave me correct output. In short I was able to fulfill my need some how, but I am still blank what multiplication does internally ? When I tried to multiply current date with digit 2, it gave me some date of year 2057 !! does anyone know, what exactly happening ?
The long format displays the number of ticks after 01.01.1970, so for now its about 43 years.
* operator forces argument to be cast to number, I suppose, Date object has such casting probably with getTime().
You double the number of milliseconds - you get 43 more years, hence the 2057 (or so) year.
What you are getting when you multiply, is ticks
Visit: How to convert JavaScript date object into ticks
Also, when you * 2 it, you get the double value of ticks, so the date is of future
var date = new Date()
var ticks = date.getTime()
ref: Javascript Date Ticks
getTime returns the number of milliseconds since January 1, 1970. So when you * 1 it, you might have got value of this milliseconds. When you * 2 it, those milliseconds are doubled, and you get date of 2057!!
Dates are internally stored as a timestamp, which is a long-object (more info on timestamps). This is why you can create Dates with new Date(long). If you try to multiply a Date with an integer, this is what happens:
var date = new Date();
var longFormat = date*1;
// date*1 => date.getTime() * 1
console.log(longFormat); // output is 1380.....
Javascript tries to find the easiest conversion from date to a format that can be multiplied with the factor 1, which is in this case the internal long format
Just use a date object methods.
Read the docs: JavaScript Date object
var miliseconds=yourDateObject.getMiliseconds();
If You want to get ticks:
var ticks = ((yourDateObject.getTime() * 10000) + 621355968000000000);
or
var ticks = someDate.getTime();
Javascript date objects are based on a UTC time value that is milliseconds since 1 January 1970. It just so happens that Java uses the same epoch but the time value is seconds.
To get the time value, the getTime method can be used, or a mathematic operation can be applied to the date object, e.g.
var d = new Date();
alert(d.getTime()); // shows time value
alert(+d); // shows time value
The Date constructor also accepts a time value as an argument to create a date object, so to copy a date object you can do:
var d2 = new Date(+d);
If you do:
var d3 = new Date(2 * d);
you are effectively creating a date that is (very roughly):
1970 + (2013 - 1970) * 2 = 2056
You could try the parsing functionality of the Date constructor, whose result you then can stringify:
>
new Date("04/06/13").toString()
"Sun Apr 06 1913 00:00:00 GMT+0200"
// or something
But the parsing is implementation-dependent, and there won't be many engines that interpret your odd DD/MM/YY format correctly. If you had used MM/DD/YYYY, it probably would be recognized everywhere.
Instead, you want to ensure how it is parsed, so have to do it yourself and feed the single parts into the constructor:
var parts = "04/06/13".split("/"),
date = new Date(+parts[2]+2000, parts[1]-1, +parts[0]);
console.log(date.toString()); // Tue Jun 04 2013 00:00:00 GMT+0200
My js code is as follows:-
var earlierdate=new Date(2012,09,22);
alert(earlierdate.getDay());
var date2 = new Date('2012,09,22');
alert(date2.getDay());
The problem is first alert gives me 1 0r Monday(which is incorrect) and second one gives me 6 or sat which is correct. So date given in quotes is giving correct result. Now if want to use variables instead of hard-coded values like
var date1 = new Date(a,b,c);
alert(date1.getDay());
What should be the syntax. I have tried a lot of variations but failed.
Thanks in advance.
The month parameter of Date is 0-indexed.
month
Integer value representing the month, beginning with 0 for January to
11 for December.
So if you mean September, that should be var earlierdate=new Date(2012, 8, 22);
//Option 1
var myDate=new Date();
myDate.setFullYear(2010,0,14);
//Option 2 (Neater)
var myDate=new Date(2010,0,14);
This will set the time to 14th January 2010.