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 sucstract hours from datetime.
I tried with setHours and AddHours and both of the times in the debugger i see "undefined".
This is my function, everyting that i marked is things that i tried:
function timeLine(hours) {
var dt = new Date();
debugger;
//var calculatedDateTime = dt.setHours(dt.setHours() - (hours));
//var calculatedDateTime = dt.setHours(hours);
//var calculatedDateTime = dt.(hours);
//var calculatedDateTime = dt.AddHours(dt.AddHours() - (hours));;
$("#tblAlarms").find("tr").each(function (index) {
if (index === 0) return;
var filterColumn = $(this).find("td").eq(4);
if (Date.parse(filterColumn) > calculatedDateTime)
$(this).show();
else
$(this).hide();
}
This is where i set the hours:
onclick="timeLine(-12)">12
Can someone help me please?
Try
(dateNow - datePast) / 3600000
This will give you the number of hours.
and
new Date(date - hours * 3600000)
will substract an amount of hours from your date and give you the new date.
You can use the AddHours() to subtract the hours from Date by passing negative values.
DateTime dt = dt.AddHours(-6);
var d = new Date();
var hours = 12;
d.setHours(d.getHours() - hours);
alert(d);
Fiddle here
Use moment for any date/time calculations:
Example:
moment(date1).diff(date2,'minutes');
moment(date1).diff(date2,'days');
I have an ISODateTime format :
2013-11-21T20:58:03+0000
How to convert it to milliseconds in AngularJS.
I used DateTime.Parse() => it works on chrome but fails on ios.
Any other way to implement the same?
My main aim for this is to find difference (in minutes) between current time and this time :
var diff= (new Date(new Date().getTime() - Date.parse(item['myDate']))).getMinutes();
where item['myDate'] = 2013-11-21T20:58:03+0000
To be sure that it will work on any browser (like iOS safari) we can just split time and create new date instance.
Try:
$scope.item = {};
$scope.item.myDate = '2013-11-21T20:58:03+0000';
var arr = $scope.item.myDate.split(/[- :+T]/);
var fixedDate = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4]);
var currTime = new Date().getTime();
var fixedTime = fixedDate.getTime();
var tot = currTime - fixedTime;
var minutes = tot / 1000 / 60;
console.log('tot', tot);
console.log('minutes', minutes);
Demo Fiddle
I want to adjust the Date object to always be 4 hours offset. How would I achieve this?
var d = new Date();
// d would be 4 hours in the past
Something like this:
d.setHours(d.getHours()-4);
Date.withOffset = function( offset ){
var r = new Date();
r.setHours(r.getHours()+offset);
return r;
};
var d = Date.withOffset( -4 )
// d would be 4 hours in the past
You may come up with a better name.
If you wish to break all javascript on your page you may of course use:
Date = function () {
var old = Date;
function broken() {
var r = new old();
r.setHours(r.getHours()-4);
return r;
}
broken.fix = function () {
Date = old;
};
return broken;
}();
You can then fix it by calling Date.fix()
You can create a date object with a particular date. Just subtract the correct milliseconds from the current time and pass that to the date function:
var d = new Date(new Date().getTime() - 1000*60*60*4);
or you can manually set the hours
var d = new Date();
d.setHours((12 + (d.getHours() - 4))%12)
I am looking for a way to do proper subtraction between two javascript Date objects and get the day delta.
This is my approach but it fails for todays date as an input:
<script type="text/javascript">
function getDayDelta(incomingYear,incomingMonth,incomingDay){
var incomingDate = new Date(incomingYear,incomingMonth,incomingDay);
var today = new Date();
var delta = incomingDate - today;
var resultDate = new Date(delta);
return resultDate.getDate();
}
//works for the future dates:
alert(getDayDelta(2009,9,10));
alert(getDayDelta(2009,8,19));
//fails for the today as input, as expected 0 delta,instead gives 31:
alert(getDayDelta(2009,8,18));
</script>
What would be a better approach for this ?
The month number in the Date constructor function is zero based, you should substract one, and I think that is simplier to calculate the delta using the timestamp:
function getDayDelta(incomingYear,incomingMonth,incomingDay){
var incomingDate = new Date(incomingYear,incomingMonth-1,incomingDay),
today = new Date(), delta;
// EDIT: Set time portion of date to 0:00:00.000
// to match time portion of 'incomingDate'
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
today.setMilliseconds(0);
// Remove the time offset of the current date
today.setHours(0);
today.setMinutes(0);
delta = incomingDate - today;
return Math.round(delta / 1000 / 60 / 60/ 24);
}
getDayDelta(2008,8,18); // -365
getDayDelta(2009,8,18); // 0
getDayDelta(2009,9,18); // 31
(2009,8,18) is NOT August 18th. It's September 18th.
You could call getTime() on each date object, then subtract the later from the earlier. This would give you the number of milliseconds difference between the two objects. From there, it's easy to get to days.
A couple of hiccups to watch for, though: 1) daylight savings time, and 2) ensuring your times are coming from the same time zone.
This will work better, but it doesn't properly deal with negative result values. You might want to simply parse the values yourself and deal with them.
function getDayDelta(incomingYear,incomingMonth,incomingDay){
var incomingDate = new Date(incomingYear,incomingMonth-1,incomingDay);
var today = new Date();
today = new Date(Date.parse(today.format("yyyy/MM/dd")));
var delta = incomingDate - today;
if (delta == 0) { return 0; }
var resultDate = new Date(delta);
return resultDate.getDate();
}
//works for the future dates:
alert(getDayDelta(2009,9,10));
alert(getDayDelta(2009,8,19));
alert(getDayDelta(2009, 8, 18));