I am trying to convert a UNIX timestamp to a JavaScript date object. It works perfectly fine for all other inputs except the following,
dt = new Date(1421020800 * 1000);
dt.getMonth(); // yields '0'
For some mysterious reason, the ouput value is 0 for month, whereas the expected value as per this link should be 1.
Does the month in Javascript date object starts with 0?
It's normal - you can read in W3Schools (or anywhere else)
The getMonth() method returns the month (from 0 to 11) for the
specified date, according to local time.
Note: January is 0, February is 1, and so on.
Related
I have an object with a date property. I set the date to 01 April 2000 and can see in the debugger that it is set properly to the same date. However when I do a getMonth() on the same date object it returns month as 3 ( March ) . Why is this happening. Does it have anything to do with UTC or Localization both of which i am not using ?
You need +1 for getMonth function
var month = date.getMonth() + 1
this is normal behavior. Months starts with Zero(i.e january is 0). thats why its giving 3 for april. use adding 1 with month to get exact month's digit value.
i guess, to help indexing javascript starts month with zero.
suppose an array of months in string form then we dont have to worry to fetch correct month from string.
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 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 have a date object:
var thedate = new Date("2012-05-02T11:00:00.000+0000");
When I do getMonth() I get 4, but when I do getDay() I get 3? I want to make it so that when I call getDay, I get what’s reflected in the original string (2). I could just subtract 1 from getDay(), but I’m not sure if that’s the right way to do it, and whether it applies to all dates.
According to MDN, getMonth will return a number in the range 0-11 (so 0 is for January), and getDay will return the day of the week in the range 0-6 (so 0 is for Sunday). If you want to get the day in month, you should use getDate, which will return a number in the range 1-31.
getDay/getMonth will return the index of the day, which starts from 0, therefore +1.
getDay() Returns the day of the week (from 0-6)
Read here: http://www.w3schools.com/jsref/jsref_obj_date.asp
I'm looking for a way to change a picture on my website if the time is later than 21pm on a certain day. Basically I don't want to have to do it manually since I won't have access to a computer when I need to switch the image. I cannot use PHP as the website I am working on does not support PHP (only ASP).
I guess it could be done in Javascript.
Edit : the picture need to be changed once at 21 and never be changed again not even the day after.
The answer already posted should work. However, take care, that you have to trigger such function, you can do it on the page onload event, (if you want to check just once when the user load the page); or you can set a timer that every 10 minutes (or the minutes you want), trigger such function. It depends by the nature of your website and the time spent by the user on the page (if it's few minutes at most, it doesen't worth)
You can create a Date object and get the current hour of the day (according to the client), and change the source of the image based on that hour:
var d = new Date();
var hour = d.getHours();
if(hour > 21) {
document.getElementById("imageID").src = "newImage.png";
}
Update (based on comments)
If you want the image to change at 21:00 on a certain date, and to remain as that new image after that date (and you really want to use JavaScript for this), then you can create a Date object with your specified date/time (e.g. var d = new Date('June 18, 2011 21:00:00');) and you can then compare the current date with your specified date when the page loads:
var d = new Date('June 18, 2011 21:00:00');
var current = new Date();
if(current > d) {
document.getElementById("imageID").src = "newImage.png";
}
You can see an example of this here. (Comment out the first line, and comment in the second line to see the difference of future and past dates).
You should do this in the backend, this is extra overhead in the client for no real reason, but let's give it a try in JS though!
var myDate = new Date();
var curr_hour = myDate.getHours();
var day = myDate.getDate();
var month = myDate.getMonth()+1;
var year = myDate.getFullYear();
if( curr_hour>=21 && ( day==17 && month==5 && year==2011 ) )
document.getElementById('myPicture').src = 'source.jpg';
the picture will be changed after 21, of 05 / 17 / 2011 (and only for that day)
use the javascripit date object?
EDITING Per #Joe's suggestion
//initialize date object
function CheckAndChangeImage() {
var d = new Date();
var currentHour = d.getHours(); //note 0-23
var currentDay = d.getDate();
var currentMonth = d.getMonth();
var currentYear = d.getYear(); // 2011 == 111
if (currentHour >= 21 && currentDay >= 17 && currentMonth >= 5 && currentYear >= 111 )
{
//do something on late night (21,22,23 hundread hrs)
document.getElementById('thePicture').src = 'lateNight.png';
}
/* commented out, per OP edit
else
{
//do something else
document.getElementById('thePicture').src = 'OtherPicture.png';
} */
}
setInterval(CheckAndChangeImage,60000); //60,000 milliseconds in a minute`
this will check that it is equal too or greater than 21hrs on the users machine and the date is after today. the setInterval(function,ms) checks every minute so if the user comes to your site at 20:59 it should still change at 21:00. You mentioned the picture needs to be changed once and never again. This solution is very ugly. I would suggest setting up a cron on the local machine to run at 21:00 and update the time site wide. Perhaps PHP could do this, but PHP is not my language of choice. I would likely use python and/or bash for this task. But you could likely accomplish it in Perl. I would suggest an X/HTML parser.
more on the date object
getDate() Returns the day of the
month (from 1-31)
getDay() Returns the day of the week (from 0-6)
getFullYear() Returns the year (four digits)
getHours() Returns the hour (from 0-23)
getMilliseconds() Returns the milliseconds (from 0-999)
getMinutes() Returns the minutes (from 0-59)
getMonth() Returns the month (from 0-11)
getSeconds() Returns the seconds (from 0-59)
getTime() Returns the number of milliseconds since midnight Jan 1,
1970
getTimezoneOffset() Returns the time difference between GMT and local
time, in minutes
getUTCDate() Returns the day of the month, according to universal time
(from 1-31)
getUTCDay() Returns the day of the week, according to universal time
(from 0-6)
getUTCFullYear() Returns the year, according to universal time
(four digits)
getUTCHours() Returns the hour, according to universal time (from
0-23)
getUTCMilliseconds() Returns the milliseconds, according to
universal time (from 0-999)
getUTCMinutes() Returns the minutes, according to universal time
(from 0-59)
getUTCMonth() Returns the month, according to universal time (from
0-11)
getUTCSeconds() Returns the seconds, according to universal time
(from 0-59)
getYear() Deprecated. Use the getFullYear() method instead
parse() Parses a date string and returns the number of milliseconds
since midnight of January 1, 1970
setDate() Sets the day of the month (from 1-31)
setFullYear() Sets the year (four digits)
setHours() Sets the hour (from 0-23)
setMilliseconds() Sets the milliseconds (from 0-999)
setMinutes() Set the minutes (from 0-59)
setMonth() Sets the month (from 0-11)
setSeconds() Sets the seconds (from 0-59)
setTime() Sets a date and time by adding or subtracting a specified
number of milliseconds to/from
midnight January 1, 1970
setUTCDate() Sets the day of the month, according to universal time
(from 1-31)
setUTCFullYear() Sets the year, according to universal time (four
digits)
setUTCHours() Sets the hour, according to universal time (from
0-23)
setUTCMilliseconds() Sets the milliseconds, according to universal
time (from 0-999)
setUTCMinutes() Set the minutes, according to universal time (from
0-59)
setUTCMonth() Sets the month, according to universal time (from
0-11)
setUTCSeconds() Set the seconds, according to universal time (from
0-59)
setYear() Deprecated. Use the setFullYear() method instead
toDateString() Converts the date portion of a Date object into a
readable string
toGMTString() Deprecated. Use the toUTCString() method instead
toLocaleDateString() Returns the date portion of a Date object as a
string, using locale conventions
toLocaleTimeString() Returns the time portion of a Date object as a
string, using locale conventions
toLocaleString() Converts a Date object to a string, using locale
conventions
toString() Converts a Date object to a string
toTimeString() Converts the time portion of a Date object to a
string
toUTCString() Converts a Date object to a string, according to
universal time
UTC() Returns the number of milliseconds in a date string since
midnight of January 1, 1970, according
to universal time
valueOf() Returns the primitive value of a Date objecti
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date provides and overview of the date object
so too does w3schools
http://www.w3schools.com/jsref/jsref_obj_date.asp