I want change the time on a specified date, i tried as following js code, but doesn't work if... in line number 11. What do i do?
var interval = self.setInterval("clock()", 1000);
function clock() {
var date = new Date();
var hourOffset = 3;
date.setUTCHours(date.getUTCHours(), date.getUTCMinutes());
var time = date.getTime();
date.setUTCFullYear(date.getUTCFullYear(), 3, 21);
var dstStart = date.getTime();
date.setUTCFullYear(date.getUTCFullYear(), 9, 22);
var dstEnd = date.getTime();
if (time > dstStart && time < dstEnd) hourOffset = 4; // This is line 11
date.setUTCHours(date.getUTCHours() + hourOffset, date.getUTCMinutes() + 30);
var output = date.getUTCHours() + ":" + date.getUTCMinutes() + ":" + date.getUTCSeconds();
document.getElementById("clock").innerHTML = output
}
I mean is this line that doesn't work:
if (time > dstStart && time < dstEnd) hourOffset = 4;
DEMO: http://jsfiddle.net/bFzny/
I'm not familiar with the date functions, but I can tell you that time is less than dstStart, which is why hourOffset is staying at 3. Also, months are 0 based indices, not 1 based. March would be 2, while September would be 8. http://jsfiddle.net/bFzny/4/ This might help you some. Remember, when using jsfiddle you don't need to enclose the code in tags.
Related
It amazes me that JavaScript's Date object does not implement an add function of any kind.
I simply want a function that can do this:
var now = Date.now();
var fourHoursLater = now.addHours(4);
function Date.prototype.addHours(h) {
// How do I implement this?
}
I would simply like some pointers in a direction.
Do I need to do string parsing?
Can I use setTime?
How about milliseconds?
Like this:
new Date(milliseconds + 4*3600*1000 /* 4 hours in ms */)?
This seems really hackish though - and does it even work?
JavaScript itself has terrible Date/Time API's. Nonetheless, you can do this in pure JavaScript:
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
Date.prototype.addHours= function(h){
this.setHours(this.getHours()+h);
return this;
}
Test:
alert(new Date().addHours(4));
The below code will add 4 hours to a date (example, today's date):
var today = new Date();
today.setHours(today.getHours() + 4);
It will not cause an error if you try to add 4 to 23 (see the documentation):
If a parameter you specify is outside of the expected range, setHours() attempts to update the date information in the Date object accordingly
It is probably better to make the addHours method immutable by returning a copy of the Date object rather than mutating its parameter.
Date.prototype.addHours= function(h){
var copiedDate = new Date(this.getTime());
copiedDate.setHours(copiedDate.getHours()+h);
return copiedDate;
}
This way you can chain a bunch of method calls without worrying about state.
The version suggested by kennebec will fail when changing to or from DST, since it is the hour number that is set.
this.setUTCHours(this.getUTCHours()+h);
will add h hours to this independent of time system peculiarities.
Jason Harwig's method works as well.
Get a date exactly two hours from now, in one line.
You need to pass milliseconds to new Date.
let expiryDate = new Date(new Date().setHours(new Date().getHours() + 2));
or
let expiryDate2 = new Date(Date.now() + 2 * (60 * 60 * 1000) );
let nowDate = new Date();
let expiryDate = new Date(new Date().setHours(new Date().getHours() + 2));
let expiryDate2 = new Date(Date.now() + 2 * (60 * 60 * 1000) );
console.log('now', nowDate);
console.log('expiry', expiryDate);
console.log('expiry 2', expiryDate2);
You can use the Moment.js library.
var moment = require('moment');
foo = new moment(something).add(10, 'm').toDate();
I also think the original object should not be modified. So to save future manpower here's a combined solution based on Jason Harwig's and Tahir Hasan answers:
Date.prototype.addHours= function(h){
var copiedDate = new Date();
copiedDate.setTime(this.getTime() + (h*60*60*1000));
return copiedDate;
}
If you would like to do it in a more functional way (immutability) I would return a new date object instead of modifying the existing and I wouldn't alter the prototype but create a standalone function. Here is the example:
//JS
function addHoursToDate(date, hours) {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
//TS
function addHoursToDate(date: Date, hours: number): Date {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
let myDate = new Date();
console.log(myDate)
console.log(addHoursToDate(myDate,2))
There is an add in the Datejs library.
And here are the JavaScript date methods. kennebec wisely mentioned getHours() and setHours();
Check if it’s not already defined. Otherwise, define it in the Date prototype:
if (!Date.prototype.addHours) {
Date.prototype.addHours = function(h) {
this.setHours(this.getHours() + h);
return this;
};
}
This is an easy way to get an incremented or decremented data value.
const date = new Date()
const inc = 1000 * 60 * 60 // an hour
const dec = (1000 * 60 * 60) * -1 // an hour
const _date = new Date(date)
return new Date(_date.getTime() + inc)
return new Date(_date.getTime() + dec)
Another way to handle this is to convert the date to unixtime (epoch), then add the equivalent in (milli)seconds, then convert it back. This way you can handle day and month transitions, like adding 4 hours to 21, which should result in the next day, 01:00.
SPRBRN is correct. In order to account for the beginning/end of the month and year, you need to convert to Epoch and back.
Here's how you do that:
var milliseconds = 0; //amount of time from current date/time
var sec = 0; //(+): future
var min = 0; //(-): past
var hours = 2;
var days = 0;
var startDate = new Date(); //start date in local time (we'll use current time as an example)
var time = startDate.getTime(); //convert to milliseconds since epoch
//add time difference
var newTime = time + milliseconds + (1000*sec) + (1000*60*min) + (1000*60*60*hrs) + (1000*60*60*24*days);
var newDate = new Date(newTime); //convert back to date; in this example: 2 hours from right now
Or do it in one line (where variable names are the same as above:
var newDate =
new Date(startDate.getTime() + millisecond +
1000 * (sec + 60 * (min + 60 * (hours + 24 * days))));
For a simple add/subtract hour/minute function in JavaScript, try this:
function getTime (addHour, addMin){
addHour = (addHour ? addHour : 0);
addMin = (addMin ? addMin : 0);
var time = new Date(new Date().getTime());
var AM = true;
var ndble = 0;
var hours, newHour, overHour, newMin, overMin;
// Change form 24 to 12 hour clock
if(time.getHours() >= 13){
hours = time.getHours() - 12;
AM = (hours>=12 ? true : false);
}else{
hours = time.getHours();
AM = (hours>=12 ? false : true);
}
// Get the current minutes
var minutes = time.getMinutes();
// Set minute
if((minutes + addMin) >= 60 || (minutes + addMin) < 0){
overMin = (minutes + addMin) % 60;
overHour = Math.floor((minutes + addMin - Math.abs(overMin))/60);
if(overMin < 0){
overMin = overMin + 60;
overHour = overHour-Math.floor(overMin/60);
}
newMin = String((overMin<10 ? '0' : '') + overMin);
addHour = addHour + overHour;
}else{
newMin = minutes + addMin;
newMin = String((newMin<10 ? '0' : '') + newMin);
}
// Set hour
if((hours + addHour >= 13) || (hours + addHour <= 0)){
overHour = (hours + addHour) % 12;
ndble = Math.floor(Math.abs((hours + addHour)/12));
if(overHour <= 0){
newHour = overHour + 12;
if(overHour == 0){
ndble++;
}
}else{
if(overHour == 0){
newHour = 12;
ndble++;
}else{
ndble++;
newHour = overHour;
}
}
newHour = (newHour<10 ? '0' : '') + String(newHour);
AM = ((ndble + 1) % 2 === 0) ? AM : !AM;
}else{
AM = (hours + addHour == 12 ? !AM : AM);
newHour = String((Number(hours) + addHour < 10 ? '0': '') + (hours + addHour));
}
var am = (AM) ? 'AM' : 'PM';
return new Array(newHour, newMin, am);
};
This can be used without parameters to get the current time:
getTime();
Or with parameters to get the time with the added minutes/hours:
getTime(1, 30); // Adds 1.5 hours to current time
getTime(2); // Adds 2 hours to current time
getTime(0, 120); // Same as above
Even negative time works:
getTime(-1, -30); // Subtracts 1.5 hours from current time
This function returns an array of:
array([Hour], [Minute], [Meridian])
If you need it as a string, for example:
var defaultTime: new Date().getHours() + 1 + ":" + new Date().getMinutes();
I think this should do the trick
var nextHour = Date.now() + 1000 * 60 * 60;
console.log(nextHour)
You can even format the date in desired format using the moment function after adding 2 hours.
var time = moment(new Date(new Date().setHours(new Date().getHours() + 2))).format("YYYY-MM-DD");
console.log(time);
A little messy, but it works!
Given a date format like this: 2019-04-03T15:58
//Get the start date.
var start = $("#start_date").val();
//Split the date and time.
var startarray = start.split("T");
var date = startarray[0];
var time = startarray[1];
//Split the hours and minutes.
var timearray = time.split(":");
var hour = timearray[0];
var minute = timearray[1];
//Add an hour to the hour.
hour++;
//$("#end_date").val = start;
$("#end_date").val(""+date+"T"+hour+":"+minute+"");
Your output would be: 2019-04-03T16:58
The easiest way to do it is:
var d = new Date();
d = new Date(d.setHours(d.getHours() + 2));
It will add 2 hours to the current time.
The value of d = Sat Jan 30 2021 23:41:43 GMT+0500 (Pakistan Standard Time).
The value of d after adding 2 hours = Sun Jan 31 2021 01:41:43 GMT+0500 (Pakistan Standard Time).
I'm trying to write a statement that says "if time is this and less than that then". I can use get hours and get min. However, I'm having problems combining a time such as 9:30.
Example,
var now = new Date();
var hour = now.getHours();
var day = now.getDay();
var mintues = now.getMinutes();
if (day == 0 && hour >= 9 && hour <= 11 && mintues >= 30) {
document.write(now);
}
This only if the time is less between 9:30 10. As soon as the clock hits 10 the minutes are then < 30 and the script breaks.
Any thoughts on how to better incorporate the time function to make this theory work?
Thanks,
use new Date().getTime() returns milliseconds for much easier comparison. This way there is no need to check hour, min, second, millisecond. Fiddle link
var d930 = new Date(2010, 12, 21, 9, 30, 0, 0), // today 9:30:00:000
d931 = new Date(2010, 12, 21, 9, 31, 0, 0), // today 9:31:00:000
t930 = d930.getTime(),
t931 = d931.getTime();
console.log(t931 > t930);
This way your code can check against a static 9:30 time.
var time930 = new Date(2010, 12, 21, 9, 30, 0, 0).getTime(),
sunday = 0,
now = new Date();
if(now.getDay() == sunday && now.getTime() >= time930){
/* do stuff */
}
You have a few typos and basic javascript errors.
Might wanna brush up on the basics.
W3Schools is where I learned all I know.
It works fine if you fix them...
var now = new Date();
var hour = now.getHours();
var day = now.getDay();
var minutes = now.getMinutes();
if(day == 0 && hour == 9 && minutes < 30 && minutes > 10 || day == 0 && hour == 9)
document.write('Time is between 9:10 and 9:30');
Think of the if statement as basic logic.
If the day is Sunday(0)
AND the hour is 9
AND the minutes are greater than 10
AND the minutes are less than 10
OR the day is Sunday(0)
AND the hour is before 9.
var now = new Date();
var closeTime = new Date();
closeTime.setHours(9); closeTime.setMinutes(30);
console.log(now, closeTime, now.getTime() >= closeTime.getTime());
close time is based on today, then we just change the hours and minutes to 9:30.
I made this solution simple and easy to read (thus easy to adjust).
// we need a function that makes hours and minutes a two digit number
Object.prototype.twoDigits = function () {
return ("0" + this).slice(-2);
}
// get current date and time
let now = new Date();
// compile the current hour and minutes in the format 09:35
timeOfDay = now.getHours().twoDigits() + ':' + now.getMinutes().twoDigits();
// test if timeOfDay is within a given time frame
if ('09:30' <= timeOfDay && timeOfDay <= '11:30') {
console.log('inside time frame');
} else {
console.log('outside time frame');
}
I had a similar problem to solve today, I setup a little component that returns if a place of business is open or not. Got the time by dividing the minutes by 100 then adding it to the hours. So 8:30 is represented as 8.3
let d = new Date()
let day = d.getDay()
let hours = d.getHours()
let minutes = d.getMinutes() / 100
let time = hours + minutes
if (day == 1) {
if (time > 8.3 && time < 17.3) {
setIsOpen(true)
} else {
setIsOpen(false)
}
}
if the hour is less than 9, true
or
if hour is 9 and minutes lt 30, true
so that would look like
if ((hour < 9) || (hour == 9 && minutes < 30))
Use words to figure out your logic. Symbols are just shortcuts.
One way is to do a direct comparison on date objects. Choose an arbitrary year, month and day, and then incorporate your times as follows:
var older = new Date("1980-01-01 12:15");
var newer = new Date("1980-01-01 12:30");
if (newer > older){
alert("Newer time is newer");
} else {
alert ("The time is not newer");
}
The MDC documentation on the Date object will help with some more details. The bottom line is that if you want to compare times, you don't actually need to call any methods on the objects, and it's possible to directly compare them. The date() object can take a variety of strings to assign a new time to the returned instance, these are from the MDC documentation:
today = new Date();
birthday = new Date("December 17, 1995 03:24:00");
birthday = new Date(1995,11,17);
birthday = new Date(1995,11,17,3,24,0);
As you can see, it's pretty simple. Don't complicate, and have a look through the documentation :)
While we're here, here's a test using your example:
var base = new Date("1980-01-01 9:30");
var test = new Date("1980-01-01 9:30:01");
if (test >= base){
alert("test time is newer or equal to base time");
} else {
alert ("test time is older than 9.30");
}
Try this:
var now = new Date();
var hour = now.getHours();
var mintues = now.getMinutes();
if(
(hour*60 + mintues) > 570 &&
hour <= 11
)
{
document.write(now);
}
I don't quite fully understand your question but hope this helps.
c = new Date();
nhour = c.getHours();
nmin = c.getMinutes();
if(nmin <= 9) {
nmin = "0" + nmin;
}
if(nhour <= 9) {
nhour = "0" + nhour;
}
newtime = nhour + "" + nmin;
if(newtime <= 0930){
alert("It is before 9:30am or earlier");
}
Can someone please explain why these 3 different lines that suppose to produce the exact same result, give three different results?
The only accurate one is the 2'nd line (Date.now()). Unfortunately, this is the only one I can't use.
function show_ts_date(idx, ts)
{
var a = new Date(ts * 1000);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
var sec = a.getSeconds();
var formattedTime = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
alert(idx+'. timestamp: '+ts+' Date: '+formattedTime);
}
var currentdate = new Date();
//line 1: (produces wrong timestamp - it gives the wrong hour (-4) when I convert back to dateTime)
timestamp_1 = Math.floor(new Date(currentdate.getFullYear()+'-'+(currentdate.getMonth()+1)+'-'+currentdate.getDate()+'T'+currentdate.getHours()+':'+currentdate.getMinutes()+':00') / 1000);
show_ts_date(1, timestamp_1);
//line 2 (produces correct timastamp - it gives the correct hour when I convert back to DateTime.)
timestamp_2 = Math.floor(Date.now() / 1000);
show_ts_date(2, timestamp_2);
//line 3 (produces wrong timestamp - it gives the wrong hour (+3) when I convert back to dateTime)
let dat = new Date(Date.UTC(currentdate.getFullYear(), currentdate.getMonth(), currentdate.getDate(), currentdate.getHours(), currentdate.getMinutes(), 00));
timestamp_4 = Math.floor( dat/ 1000);
show_ts_date(4, timestamp_4);
Well, assuming that Date.now() returns the real accurate value (I doubt it is always the case, But that's what I'm left with. you can always convert it back to Date and check if the right date & time came back),
I wrote this function that will compare between the right and wrong timestamps and will add (or decrease) the number of milliseconds from (or to) the false timestamp - turning it in to a correct one:
function getTimestampMilisecondsGap()
{
var currentdate = new Date();
timestamp_1 = Math.floor(new Date(currentdate.getFullYear()+'-'+(currentdate.getMonth()+1)+'-'+currentdate.getDate()+'T'+currentdate.getHours()+':'+currentdate.getMinutes()+':00') / 1000);
//let dat = new Date(Date.UTC(currentdate.getFullYear(), currentdate.getMonth(), currentdate.getDate(), currentdate.getHours(), currentdate.getMinutes(), 00));
//timestamp_1 = Math.floor( dat/ 1000);
timestamp_2 = Math.floor(Date.now() / 1000); //this one is suppose to produce a correct timestamp
var addTimeStampMilisecs = 0;
if (timestamp_2 > timestamp_1)
{
addTimeStampMilisecs = timestamp_2-timestamp_1;
}
else if (timestamp_2 < timestamp_1)
{
addTimeStampMilisecs = timestamp_1-timestamp_2;
}
return addTimeStampMilisecs;
}
//writing a timestamp to the database
var destinationDateTimeStr = document.getElementById("dateyear").value+"-"+document.getElementById("datemonth").value+"-"+document.getElementById("dateday").value+"T"+document.getElementById("datehour").value+":"+document.getElementById("dateminute").value+":00";
var date2 = new Date(destinationDateTimeStr);
var eventDateTS = Math.floor(date2 / 1000); //convert to timestamp (with incorrect timezone)
eventDateTS += getTimestampMilisecondsGap(); //add (or decrese) the number of miliseconds from the timestamp because this function that generates the tmestamp returns a wrong number (the hour in the converted date is wrong)
//write the correct eventDateTS to your DB here...
I'm using moment.js and would like to create an array that contains all of the times in 15 minute intervals from the current time. So for example:
Current time is 1:35pm. The next time would be 1:45pm, then 2:00, 2:15, 2:30, 2:45, etc. up until a certain point.
I'm really not sure how to this. Would anyone be able to point me in the right direction?
Try this:
function calculate(endTime) {
var timeStops = [];
var startTime = moment().add('m', 15 - moment().minute() % 15);
while(startTime <= endTime){
timeStops.push(new moment(startTime));
startTime.add('m', 15);
}
return timeStops;
}
usage:
calculate(moment().add('h', 1));
This will return time intervals of every quarter of hour (like you said) h:15, h:30, h:45, h+1:00... It also contains seconds, so you might set seconds to 0, since I was not sure if you need them or not.
You also can see working example on FIDDLE
I'm not as familiar with momentjs but this is relatively easy to do in pure Javascript. To get the closest 15 minutes you can use this solution here. Then if you put that in a date variable you can just add 15 minutes as many times as you want! So the resulting Javascript is:
var d = new Date();
var result = "";
for (var idx = 0; idx < 3; idx++)
{
var m = (((d.getMinutes() + 7.5)/15 | 0) * 15) % 60;
var h = ((((d.getMinutes()/105) + .5) | 0) + d.getHours()) % 24;
d = new Date(d.getYear(), d.getMonth(), d.getDay(), h, m, 0, 0);
if (idx > 0) result += ", ";
result += ("0" + h).slice(-2) + ":" + ("0" + m).slice(-2);
d = addMinutes(d, 15);
}
SEE THIS IN A FIDDLE
Notes - I just added 15 minutes 3 times arbitrarily. You could calculate the difference between the time you want and now if you need a different number of intervals. Also note that I don't know exactly what this would do if it is almost midnight, though that would be easy enough to test and code around.
Best of luck!
function show_elapsed_time(from)
{
var time_elapsed = new Date().getTime()-from;
var date = new Date(time_elapsed);
var date_elements = (pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds())).split('');
var date_string = '';
for(i = 0; i < date_elements.length; i++)
{
date_string += '<div class="frame">' + date_elements[i] + '</div>';
}
$('#digital_clock').html(date_string);
}
show_elapsed_time(1308446047*1000)
The expected result (at the time of this post) is 0 hours, 2 minutes, .. seconds. This is as well the result given by Opera, Chrome and IE. However, Firefox returns 1 hour, 2 minutes, etc. How to fix it?
Basically:
var date = new Date(1453288); console.log(date.getHours()); // FF: 1, IE: 0, Opera 0
What I am doing is taking: new Date().getTime() - [some timestamp] == time passed
So I need to know time passed from [some timestamp] in hours, minutes and seconds.
Well, the problem is with different locale browser settings. One way to solve the problem is to use UTC specific methods, e.g. getUTCTime(). Instead, I've written this small script to do the math:
var time_elapsed = new Date().getTime()-from;
var hours = Math.floor(time_elapsed/(3600*1000));
time_elapsed -= hours*(3600*1000);
var minutes = Math.floor(time_elapsed/(60*1000));
time_elapsed -= minutes*(60*1000);
var seconds = Math.floor(time_elapsed/1000);