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
Related
After getting the value from Date.now() I have tried extracting the date like that:
Date.now().getDate()
However, the getDate() function doesn't work on it. My whole application is based on dates that are retrieved from Date.now() and I need to get current day of the month from the Date.now() value. I have done some research and I can not find a solution to it.
Date.now() doesn't returns a Date instance:
The Date.now() method returns the number of milliseconds elapsed since
January 1, 1970 00:00:00 UTC
Being a number, it doesn't have .getDate() method. But, you can make use of Date without arguments to get a Date instance which has a .getDate() method:
If no arguments are provided, the constructor creates a JavaScript
Date object for the current date and time according to system
settings.
So this should work:
new Date().getDate(); // 3
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 asking the user to input a date and time into my application. The user will input a time based on the timezone they are in. When I save this date and time to my database I want to convert the time to UTC so that when I query by time (which is done in UTC) I can find the entries.
This is what I've currently done :
var date = new Date();
var dateString = "0" + (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + time;
//format date
date = moment(dateString, "MM/DD/YYYY HH:mm a");
date = new Date(date).toISOString();
Where time is the time the user enters (ex if I want to schedule something for 11:00am, time = 11:00am)
When this is saved to the database, it looks like :
ISODate("2016-05-09T11:00:00Z") which is not correct since that is a EST saved as Zulu time.
How can I convert the time (I am using moment) to be saved as the correct Zulu time?
One option would be to use Javascript's built-in UTC functions.
JavaScript Date Reference
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
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)
For example,
new Date('2016-05-09 10:00:00')
returns Mon May 09 2016 10:00:00 GMT-0400
new Date('2016-05-09 10:00:00').getUTCHours()
returns 14
UPDATE: Examples (including .toISOString())
If we choose July 4, 2016 # 8:00 PM Eastern Time (GMT-0400), UTC would be July 5, 2016 # 00:00 (midnight):
var date = new Date('2016-07-04 20:00:00')
date.getUTCFullYear = 2016
date.getUTCMonth = 6 (0 base)
date.getUTCDate = 5
date.getUTCHours = 0
date.getUTCMinutes = 0
var date = new Date('2016-07-04 20:00:00')
date.toISOString() = "2016-07-05T00:00:00.000Z" (UTC)
To fix this issue I used the moment-timezone library.
I first set the timezone on the server since it will only be accessed by EST :
moment.tz.setDefault("America/New_York");
Then all I needed to do was set the timezone on the moment object to UTC by :
date = moment(dateString, "MM/DD/YYYY HH:mm a").tz("UTC");
This successfully converts the time from EST to UTC
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
Well, you might think that this question has already been asked, but I think it has not. The solutions I've read about all had this "jigsaw puzzle" technique (like getUTCMonth() + getUTCMinutes + ...).
But as I only want to compare the elapsed seconds between two UTC (!) dates, this does not apply.
As everybody knows, you can get the current (non-UTC) date by:
var d = new Date();
var t_millis = d.getTime();
But this is NOT what I want. I'd like to have the current system date in UTC and in milliseconds, so not mess about with strings at all. AFAIK the variable t_millis will contain the millisecond value of the current timestamp in GMT, not UTC.
(Since d is in GMT as well. Unless getTime() does a sort of implicit time zone conversion, i. e. adding the offset BEFORE giving out the milliseconds, but I've never read about that anywhere)
So is there really no other way than adding the offset to the time value?
I'm desperately missing a function like getUTCTimeMillis() known from other languages.
This is an old question but for the sake of the new visitors here is THE CORRECT ANSWER:
Date.now();
It returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC
The millisecond value of the time-of-day is going to be the same regardless of your time zone. That is, there are no time zones on planet Earth that differ from one another by a number of milliseconds greater than zero. (They may differ by an integer number of hours or even minutes, but not seconds or milliseconds.)
That said, the value you get back from getTime() is a UTC-relative timestamp. If two web browsers at widely different spots on the globe create a Date object at the same time, they'll both get the same value from .getTime() (assuming the clocks are synchronized, which is of course highly unlikely).
Here: 1338585185539 That's a timestamp I just got from my browser. I'm in Austin, TX, and now it's 4:13 in the afternoon (so that timestamp will be from slightly before that). Plug it into a Date instance on your machine and see what it says.
(edit — for posterity's sake, that timestamp is from 1 June 2012.)
how about:
var now = new Date();
var utc_now = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());
console.log('UTC: ' + utc_now) // correct UTC time but wrong timezone!
console.log('UTC (in ms): ' + utc_now.getTime())
I have used this function to solve the problem.
function getUTCNow()
{
var now = new Date();
var time = now.getTime();
var offset = now.getTimezoneOffset();
offset = offset * 60000;
return time - offset;
}
The getTime function returns the number of milliseconds elapsed since
1 January 1970 00:00:00 in the client timezone.
getTimezoneOffset return offset in minutes between Client timezone and UTC.
offset = offset * 60000; this operation transform minutes in miliseconds.
subtracting the offset get the number of milliseconds elapsed since 1
January 1970 00:00:00 UTC.
To get the timestamp from a date in UTC, you need to take in consideration the timezone and daylight savings for that date. For example, a date in January or in July could mean 1 hour difference.
The option below does just that.
Date.prototype.getUTCTime = function () {
return this.getTime() - (this.getTimezoneOffset() * 60000);
};
It can be used as in:
var date = new Date();
var timestamp = date.getUTCTime();