Put clock forward by one hour [duplicate] - javascript

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).

Related

Subtract the date from current date javascript [duplicate]

I'm creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date. I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference.
In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the getTime() method or just using the date in a numeric expression.
So to get the difference, just subtract the two dates.
To create a new date based on the difference, just pass the number of milliseconds in the constructor.
var oldBegin = ...
var oldEnd = ...
var newBegin = ...
var newEnd = new Date(newBegin + oldEnd - oldBegin);
This should just work
EDIT: Fixed bug pointed by #bdukes
EDIT:
For an explanation of the behavior, oldBegin, oldEnd, and newBegin are Date instances. Calling operators + and - will trigger Javascript auto casting and will automatically call the valueOf() prototype method of those objects. It happens that the valueOf() method is implemented in the Date object as a call to getTime().
So basically: date.getTime() === date.valueOf() === (0 + date) === (+date)
JavaScript perfectly supports date difference out of the box
https://jsfiddle.net/b9chris/v5twbe3h/
var msMinute = 60*1000,
msDay = 60*60*24*1000,
a = new Date(2012, 2, 12, 23, 59, 59),
b = new Date("2013 march 12");
console.log(Math.floor((b - a) / msDay) + ' full days between'); // 364
console.log(Math.floor(((b - a) % msDay) / msMinute) + ' full minutes between'); // 0
Now some pitfalls. Try this:
console.log(a - 10); // 1331614798990
console.log(a + 10); // mixed string
So if you have risk of adding a number and Date, convert Date to number directly.
console.log(a.getTime() - 10); // 1331614798990
console.log(a.getTime() + 10); // 1331614799010
My fist example demonstrates the power of Date object but it actually appears to be a time bomb
See JsFiddle DEMO
var date1 = new Date();
var date2 = new Date("2025/07/30 21:59:00");
//Customise date2 for your required future time
showDiff();
function showDiff(date1, date2){
var diff = (date2 - date1)/1000;
diff = Math.abs(Math.floor(diff));
var days = Math.floor(diff/(24*60*60));
var leftSec = diff - days * 24*60*60;
var hrs = Math.floor(leftSec/(60*60));
var leftSec = leftSec - hrs * 60*60;
var min = Math.floor(leftSec/(60));
var leftSec = leftSec - min * 60;
document.getElementById("showTime").innerHTML = "You have " + days + " days " + hrs + " hours " + min + " minutes and " + leftSec + " seconds before death.";
setTimeout(showDiff,1000);
}
for your HTML Code:
<div id="showTime"></div>
If you don't care about the time component, you can use .getDate() and .setDate() to just set the date part.
So to set your end date to 2 weeks after your start date, do something like this:
function GetEndDate(startDate)
{
var endDate = new Date(startDate.getTime());
endDate.setDate(endDate.getDate()+14);
return endDate;
}
To return the difference (in days) between two dates, do this:
function GetDateDiff(startDate, endDate)
{
return endDate.getDate() - startDate.getDate();
}
Finally, let's modify the first function so it can take the value returned by 2nd as a parameter:
function GetEndDate(startDate, days)
{
var endDate = new Date(startDate.getTime());
endDate.setDate(endDate.getDate() + days);
return endDate;
}
Thanks #Vincent Robert, I ended up using your basic example, though it's actually newBegin + oldEnd - oldBegin. Here's the simplified end solution:
// don't update end date if there's already an end date but not an old start date
if (!oldEnd || oldBegin) {
var selectedDateSpan = 1800000; // 30 minutes
if (oldEnd) {
selectedDateSpan = oldEnd - oldBegin;
}
newEnd = new Date(newBegin.getTime() + selectedDateSpan));
}
Depending on your needs, this function will calculate the difference between the 2 days, and return a result in days decimal.
// This one returns a signed decimal. The sign indicates past or future.
this.getDateDiff = function(date1, date2) {
return (date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24);
}
// This one always returns a positive decimal. (Suggested by Koen below)
this.getDateDiff = function(date1, date2) {
return Math.abs((date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24));
}
If using moment.js, there is a simpler solution, which will give you the difference in days in one single line of code.
moment(endDate).diff(moment(beginDate), 'days');
Additional details can be found in the moment.js page
Cheers,
Miguel
function compare()
{
var end_actual_time = $('#date3').val();
start_actual_time = new Date();
end_actual_time = new Date(end_actual_time);
var diff = end_actual_time-start_actual_time;
var diffSeconds = diff/1000;
var HH = Math.floor(diffSeconds/3600);
var MM = Math.floor(diffSeconds%3600)/60;
var formatted = ((HH < 10)?("0" + HH):HH) + ":" + ((MM < 10)?("0" + MM):MM)
getTime(diffSeconds);
}
function getTime(seconds) {
var days = Math.floor(leftover / 86400);
//how many seconds are left
leftover = leftover - (days * 86400);
//how many full hours fits in the amount of leftover seconds
var hours = Math.floor(leftover / 3600);
//how many seconds are left
leftover = leftover - (hours * 3600);
//how many minutes fits in the amount of leftover seconds
var minutes = leftover / 60;
//how many seconds are left
//leftover = leftover - (minutes * 60);
alert(days + ':' + hours + ':' + minutes);
}
alternative modificitaion extended code..
http://jsfiddle.net/vvGPQ/48/
showDiff();
function showDiff(){
var date1 = new Date("2013/01/18 06:59:00");
var date2 = new Date();
//Customise date2 for your required future time
var diff = (date2 - date1)/1000;
var diff = Math.abs(Math.floor(diff));
var years = Math.floor(diff/(365*24*60*60));
var leftSec = diff - years * 365*24*60*60;
var month = Math.floor(leftSec/((365/12)*24*60*60));
var leftSec = leftSec - month * (365/12)*24*60*60;
var days = Math.floor(leftSec/(24*60*60));
var leftSec = leftSec - days * 24*60*60;
var hrs = Math.floor(leftSec/(60*60));
var leftSec = leftSec - hrs * 60*60;
var min = Math.floor(leftSec/(60));
var leftSec = leftSec - min * 60;
document.getElementById("showTime").innerHTML = "You have " + years + " years "+ month + " month " + days + " days " + hrs + " hours " + min + " minutes and " + leftSec + " seconds the life time has passed.";
setTimeout(showDiff,1000);
}
Below code will return the days left from today to futures date.
Dependencies: jQuery and MomentJs.
var getDaysLeft = function (date) {
var today = new Date();
var daysLeftInMilliSec = Math.abs(new Date(moment(today).format('YYYY-MM-DD')) - new Date(date));
var daysLeft = daysLeftInMilliSec / (1000 * 60 * 60 * 24);
return daysLeft;
};
getDaysLeft('YYYY-MM-DD');
<html>
<head>
<script>
function dayDiff()
{
var start = document.getElementById("datepicker").value;
var end= document.getElementById("date_picker").value;
var oneDay = 24*60*60*1000;
var firstDate = new Date(start);
var secondDate = new Date(end);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
document.getElementById("leave").value =diffDays ;
}
</script>
</head>
<body>
<input type="text" name="datepicker"value=""/>
<input type="text" name="date_picker" onclick="function dayDiff()" value=""/>
<input type="text" name="leave" value=""/>
</body>
</html>
this code fills the duration of study years when you input the start date and end date(qualify accured date) of study and check if the duration less than a year if yes the alert a message
take in mind there are three input elements the first txtFromQualifDate and second txtQualifDate and third txtStudyYears
it will show result of number of years with fraction
function getStudyYears()
{
if(document.getElementById('txtFromQualifDate').value != '' && document.getElementById('txtQualifDate').value != '')
{
var d1 = document.getElementById('txtFromQualifDate').value;
var d2 = document.getElementById('txtQualifDate').value;
var one_day=1000*60*60*24;
var x = d1.split("/");
var y = d2.split("/");
var date1=new Date(x[2],(x[1]-1),x[0]);
var date2=new Date(y[2],(y[1]-1),y[0])
var dDays = (date2.getTime()-date1.getTime())/one_day;
if(dDays < 365)
{
alert("the date between start study and graduate must not be less than a year !");
document.getElementById('txtQualifDate').value = "";
document.getElementById('txtStudyYears').value = "";
return ;
}
var dMonths = Math.ceil(dDays / 30);
var dYears = Math.floor(dMonths /12) + "." + dMonths % 12;
document.getElementById('txtStudyYears').value = dYears;
}
}
If you use Date objects and then use the getTime() function for both dates it will give you their respective times since Jan 1, 1970 in a number value. You can then get the difference between these numbers.
If that doesn't help you out, check out the complete documentation: http://www.w3schools.com/jsref/jsref_obj_date.asp
var getDaysLeft = function (date1, date2) {
var daysDiffInMilliSec = Math.abs(new Date(date1) - new Date(date2));
var daysLeft = daysDiffInMilliSec / (1000 * 60 * 60 * 24);
return daysLeft;
};
var date1='2018-05-18';
var date2='2018-05-25';
var dateDiff = getDaysLeft(date1, date2);
console.log(dateDiff);
To get the date difference in milliseconds between two dates:
var diff = Math.abs(date1 - date2);
I'm not sure what you mean by converting the difference back into a date though.
Many answers here are based on a direct subtraction of Date objects like new Date(…) - new Date(…). This is syntactically wrong. Browsers still accept it because of backward compatibility. But modern JS linters will throw at you.
The right way to calculate date differences in milliseconds is new Date(…).getTime() - new Date(…).getTime():
// Time difference between two dates
let diffInMillis = new Date(…).getTime() - new Date(…).getTime()
If you want to calculate the time difference to now, you can just remove the argument from the first Date:
// Time difference between now and some date
let diffInMillis = new Date().getTime() - new Date(…).getTime()
function checkdate() {
var indate = new Date()
indate.setDate(dat)
indate.setMonth(mon - 1)
indate.setFullYear(year)
var one_day = 1000 * 60 * 60 * 24
var diff = Math.ceil((indate.getTime() - now.getTime()) / (one_day))
var str = diff + " days are remaining.."
document.getElementById('print').innerHTML = str.fontcolor('blue')
}
THIS IS WHAT I DID ON MY SYSTEM.
var startTime=("08:00:00").split(":");
var endTime=("16:00:00").split(":");
var HoursInMinutes=((parseInt(endTime[0])*60)+parseInt(endTime[1]))-((parseInt(startTime[0])*60)+parseInt(startTime[1]));
console.log(HoursInMinutes/60);

Check if date is less than 1 hour ago?

Is there a way to check if a date is less than 1 hour ago like this?
// old date
var olddate = new Date("February 9, 2012, 12:15");
// current date
var currentdate = new Date();
if (olddate >= currentdate - 1 hour) {
alert("newer than 1 hour");
else {
alert("older than 1 hour");
}
Also, different question - is there a way to add hours to a date like this?
var olddate = new Date("February 9, 2012, 12:15") + 15 HOURS; // output: February 10, 2012, 3:15
Define
var ONE_HOUR = 60 * 60 * 1000; /* ms */
then you can do
((new Date) - myDate) < ONE_HOUR
To get one hour from a date, try
new Date(myDate.getTime() + ONE_HOUR)
Using some ES6 syntax:
const lessThanOneHourAgo = (date) => {
const HOUR = 1000 * 60 * 60;
const anHourAgo = Date.now() - HOUR;
return date > anHourAgo;
}
Using the Moment library:
const lessThanOneHourAgo = (date) => {
return moment(date).isAfter(moment().subtract(1, 'hours'));
}
Shorthand syntax with Moment:
const lessThanOneHourAgo = (date) => moment(date).isAfter(moment().subtract(1, 'hours'));
the moment library can really help express this. The trick is to take the date, add time, and see if it's before or after now:
lastSeenAgoLabel: function() {
var d = this.lastLogin();
if (! moment(d).isValid()) return 'danger'; // danger if not a date.
if (moment(d).add(10, 'minutes').isBefore(/*now*/)) return 'danger'; // danger if older than 10 mins
if (moment(d).add(5, 'minutes').isBefore(/*now*/)) return 'warning'; // warning if older than 5mins
return 'success'; // Looks good!
},
Using moment will be much easier in this case, You could try this:
let hours = moment().diff(moment(yourDateString), 'hours');
It will give you integer value like 1,2,5,0etc so you can easily use condition check like:
if(hours < 1) {
Also, one more thing is you can get more accurate result of the time difference (in decimals like 1.2,1.5,0.7etc) to get this kind of result use this syntax:
let hours = moment().diff(moment(yourDateString), 'hours', true);
Let me know if you have any further query
//for adding hours to a date
Date.prototype.addHours= function(hrs){
this.setHours(this.getHours()+hrs);
return this;
}
Call function like this:
//test alert(new Date().addHours(4));
You can do it as follows:
First find difference of two dates i-e in milliseconds
Convert milliseconds into minutes
If minutes are less than 60, then it means date is within hour else not within hour.
var date = new Date("2020-07-12 11:30:10");
var now = new Date();
var diffInMS = now - date;
var msInHour = Math.floor(diffInMS/1000/60);
if (msInHour < 60) {
console.log('Within hour');
} else {
console.log('Not within the hour');
}
Plain JavaScript solution with in 12 days and 12 days ago option
const timeAgo = ( inputDate ) => {
const date = ( inputDate instanceof Date) ? inputDate : new Date(inputDate);
const FORMATTER = new Intl.RelativeTimeFormat('en');
const RANGES = {
years : 3600 * 24 * 365,
months : 3600 * 24 * 30,
weeks : 3600 * 24 * 7,
days : 3600 * 24,
hours : 3600,
minutes : 60,
seconds : 1
};
const secondsElapsed = (date.getTime() - Date.now()) / 1000;
for (let key in RANGES) {
if ( RANGES[key] < Math.abs(secondsElapsed) ) {
const delta = secondsElapsed / RANGES[key];
return FORMATTER.format(Math.round(delta), key);
}
}
}
// OUTPUTS
console.log( timeAgo('2040-12-24') )
console.log( timeAgo('6 Sept, 2012') );
console.log( timeAgo('2022-05-27T17:45:01+0000') );
let d = new Date()
console.log( "Date will change: ", timeAgo( d.setHours(24,0,0,0) ) );
// d.setDate( d.getDate() - 0 );
d.setHours(-24,0,0,0); // (H,M,S,MS) | 24 hours format
console.log("Day started: " , timeAgo( d ) );
//try this:
// to compare two date's:
<Script Language=Javascript>
function CompareDates()
{
var str1 = document.getElementById("Fromdate").value;
var str2 = document.getElementById("Todate").value;
var dt1 = parseInt(str1.substring(0,2),10);
var mon1 = parseInt(str1.substring(3,5),10);
var yr1 = parseInt(str1.substring(6,10),10);
var dt2 = parseInt(str2.substring(0,2),10);
var mon2 = parseInt(str2.substring(3,5),10);
var yr2 = parseInt(str2.substring(6,10),10);
var date1 = new Date(yr1, mon1, dt1);
var date2 = new Date(yr2, mon2, dt2);
if(date2 < date1)
{
alert("To date cannot be greater than from date");
return false;
}
else
{
alert("Submitting ...");
}
}
</Script>
Hope it will work 4 u...

How to round to nearest hour using JavaScript Date Object

I am working on a project that requires a time in the future to be set using the Date object.
For example:
futureTime = new Date();
futureTime.setHours(futureTime.getHours()+2);
My questions is; once the future date is set, how can I round to the closest full hour and then set the futureTime var with it?
For example:
Given 8:55 => var futureTime = 9:00
Given 16:23 => var futureTime = 16:00
Any help would be appreciated!
Round the minutes and then clear the minutes:
var date = new Date(2011,1,1,4,55); // 4:55
roundMinutes(date); // 5:00
function roundMinutes(date) {
date.setHours(date.getHours() + Math.round(date.getMinutes()/60));
date.setMinutes(0, 0, 0); // Resets also seconds and milliseconds
return date;
}
The other answers ignore seconds and milliseconds components of the date.
The accepted answer has been updated to handle milliseconds, but it still does not handle daylight savings time properly.
I would do something like this:
function roundToHour(date) {
p = 60 * 60 * 1000; // milliseconds in an hour
return new Date(Math.round(date.getTime() / p ) * p);
}
var date = new Date(2011,1,1,4,55); // 4:55
roundToHour(date); // 5:00
date = new Date(2011,1,1,4,25); // 4:25
roundToHour(date); // 4:00
A slightly simpler way :
var d = new Date();
d.setMinutes (d.getMinutes() + 30);
d.setMinutes (0);
Another solution, which is no where near as graceful as IAbstractDownvoteFactory's
var d = new Date();
if(d.getMinutes() >= 30) {
d.setHours(d.getHours() + 1);
}
d.setMinutes(0);
Or you could mix the two for optimal size.
http://jsfiddle.net/HkEZ7/
function roundMinutes(date) {
return date.getMinutes() >= 30 ? date.getHours() + 1 : date.getHours();
}
As a matter of fact Javascript does this default which gives wrong time.
let dateutc="2022-02-17T07:20:00.000Z";
let bd = new Date(dateutc);
console.log(bd.getHours()); // gives me 8!!!!!
it is even wrong for my local time because I am GMT+2 so it should say 9.
moment.js also does it wrong so you need to be VERY carefull
Pass any cycle you want in milliseconds to get next cycle example 1 hours
function calculateNextCycle(interval) {
const timeStampCurrentOrOldDate = Date.now();
const timeStampStartOfDay = new Date().setHours(0, 0, 0, 0);
const timeDiff = timeStampCurrentOrOldDate - timeStampStartOfDay;
const mod = Math.ceil(timeDiff / interval);
return new Date(timeStampStartOfDay + (mod * interval));
}
console.log(calculateNextCycle(1 * 60 * 60 * 1000)); // 1 hours in milliseconds

Finding date by subtracting X number of days from a particular date in Javascript

I want to find date by subtracting X number of days from a particular date in JavaScript. My JavaScript function accepts 2 parameters. One is the date value and the other is the number of days that needs to be subtracted.
For example, I pass my argument date as 27 July 2009 and i pass my other argument as 3. So i want to calculate the date 3 days before 27 July 2009. So the resultant date that we should get is 24 July 2009. How is this possible in JavaScript. Thanks for any help.
Simply:
yourDate.setDate(yourDate.getDate() - daysToSubtract);
function date_by_subtracting_days(date, days) {
return new Date(
date.getFullYear(),
date.getMonth(),
date.getDate() - days,
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds()
);
}
Never go for this solution
yourDate.setDate(yourDate.getDate() - daysToSubtract);
it wont work in case your date is 1st of any month and you want to delete some days say 1.
Instead go for below solution which will work always
var newDate = new Date( yourDate.getTime() - (days * 24 * 60 * 60 * 1000) );
Here i am posting one more answer and that will return date in specific format.
First you can get current date 10/08/2013 as below
function Cureent_Date() {
var today_GMT = new Date();
var dd = today_GMT.getDate();
var mm = today_GMT.getMonth() + 1; //January is 0!
var yyyy = today_GMT.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
current_date = mm + '/' + dd + '/' + yyyy;
alert("current_date"+current_date);
Back_date();
}
Now Get back date base on X days
function Back_date()
{
var back_GTM = new Date(); back_GTM.setDate(back_GTM.getDate() - 2); // 2 is your X
var b_dd = back_GTM.getDate();
var b_mm = back_GTM.getMonth()+1;
var b_yyyy = back_GTM.getFullYear();
if (b_dd < 10) {
b_dd = '0' + b_dd
}
if (b_mm < 10) {
b_mm = '0' +b_mm
}
var back_date= b_mm + '/' + b_dd + '/' + b_yyyy;
alert("back_date"+back_date);
}
So, Today is 10/08/2013 so it will return 10/06/2013.
Check Live Demo here
Hope this answer will help you.
Here's an example, however this does no kind of checking (for example if you use it on 2009/7/1 it'll use a negative day or throw an error.
function subDate(o, days) {
// keep in mind, months in javascript are 0-11
return new Date(o.getFullYear(), o.getMonth(), o.getDate() - days);;
}
This is what I would do. Note you can simplify the expression, I've just written it out to make it clear you are multiplying the number of days by the number of milliseconds in a day.
var newDate = new Date( yourDate.getTime() - (days * 24 * 60 * 60 * 1000) );
Just another option, which I wrote:
DP_DateExtensions Library
It's probably overkill if ALL you want to do is one calculation, but if you're going to do more date manipulation you might find it useful.
Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc.
this is in reference to above answer
check this fiddle
https://jsfiddle.net/uniyalguru/azh65aa0/
function Cureent_Date() {
var today_GMT = new Date();
var dd = today_GMT.getDate();
var mm = today_GMT.getMonth() + 1; //January is 0!
var yyyy = today_GMT.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
current_date = mm + '/' + dd + '/' + yyyy;
I have created a function for date manipulation. you can add or subtract any number of days, hours, minutes.
function dateManipulation(date, days, hrs, mins, operator) {
date = new Date(date);
if (operator == "-") {
var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
var newDate = new Date(date.getTime() - durationInMs);
} else {
var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
var newDate = new Date(date.getTime() + durationInMs);
}
return newDate;
}
Now, call this function by passing parameters. For example, here is a function call for getting date before 3 days from today.
var today = new Date();
var newDate = dateManipulation(today, 3, 0, 0, "-");

How do I get the difference between two Dates in JavaScript?

I'm creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date. I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference.
In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the getTime() method or just using the date in a numeric expression.
So to get the difference, just subtract the two dates.
To create a new date based on the difference, just pass the number of milliseconds in the constructor.
var oldBegin = ...
var oldEnd = ...
var newBegin = ...
var newEnd = new Date(newBegin + oldEnd - oldBegin);
This should just work
EDIT: Fixed bug pointed by #bdukes
EDIT:
For an explanation of the behavior, oldBegin, oldEnd, and newBegin are Date instances. Calling operators + and - will trigger Javascript auto casting and will automatically call the valueOf() prototype method of those objects. It happens that the valueOf() method is implemented in the Date object as a call to getTime().
So basically: date.getTime() === date.valueOf() === (0 + date) === (+date)
JavaScript perfectly supports date difference out of the box
https://jsfiddle.net/b9chris/v5twbe3h/
var msMinute = 60*1000,
msDay = 60*60*24*1000,
a = new Date(2012, 2, 12, 23, 59, 59),
b = new Date("2013 march 12");
console.log(Math.floor((b - a) / msDay) + ' full days between'); // 364
console.log(Math.floor(((b - a) % msDay) / msMinute) + ' full minutes between'); // 0
Now some pitfalls. Try this:
console.log(a - 10); // 1331614798990
console.log(a + 10); // mixed string
So if you have risk of adding a number and Date, convert Date to number directly.
console.log(a.getTime() - 10); // 1331614798990
console.log(a.getTime() + 10); // 1331614799010
My fist example demonstrates the power of Date object but it actually appears to be a time bomb
See JsFiddle DEMO
var date1 = new Date();
var date2 = new Date("2025/07/30 21:59:00");
//Customise date2 for your required future time
showDiff();
function showDiff(date1, date2){
var diff = (date2 - date1)/1000;
diff = Math.abs(Math.floor(diff));
var days = Math.floor(diff/(24*60*60));
var leftSec = diff - days * 24*60*60;
var hrs = Math.floor(leftSec/(60*60));
var leftSec = leftSec - hrs * 60*60;
var min = Math.floor(leftSec/(60));
var leftSec = leftSec - min * 60;
document.getElementById("showTime").innerHTML = "You have " + days + " days " + hrs + " hours " + min + " minutes and " + leftSec + " seconds before death.";
setTimeout(showDiff,1000);
}
for your HTML Code:
<div id="showTime"></div>
If you don't care about the time component, you can use .getDate() and .setDate() to just set the date part.
So to set your end date to 2 weeks after your start date, do something like this:
function GetEndDate(startDate)
{
var endDate = new Date(startDate.getTime());
endDate.setDate(endDate.getDate()+14);
return endDate;
}
To return the difference (in days) between two dates, do this:
function GetDateDiff(startDate, endDate)
{
return endDate.getDate() - startDate.getDate();
}
Finally, let's modify the first function so it can take the value returned by 2nd as a parameter:
function GetEndDate(startDate, days)
{
var endDate = new Date(startDate.getTime());
endDate.setDate(endDate.getDate() + days);
return endDate;
}
Thanks #Vincent Robert, I ended up using your basic example, though it's actually newBegin + oldEnd - oldBegin. Here's the simplified end solution:
// don't update end date if there's already an end date but not an old start date
if (!oldEnd || oldBegin) {
var selectedDateSpan = 1800000; // 30 minutes
if (oldEnd) {
selectedDateSpan = oldEnd - oldBegin;
}
newEnd = new Date(newBegin.getTime() + selectedDateSpan));
}
Depending on your needs, this function will calculate the difference between the 2 days, and return a result in days decimal.
// This one returns a signed decimal. The sign indicates past or future.
this.getDateDiff = function(date1, date2) {
return (date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24);
}
// This one always returns a positive decimal. (Suggested by Koen below)
this.getDateDiff = function(date1, date2) {
return Math.abs((date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24));
}
If using moment.js, there is a simpler solution, which will give you the difference in days in one single line of code.
moment(endDate).diff(moment(beginDate), 'days');
Additional details can be found in the moment.js page
Cheers,
Miguel
function compare()
{
var end_actual_time = $('#date3').val();
start_actual_time = new Date();
end_actual_time = new Date(end_actual_time);
var diff = end_actual_time-start_actual_time;
var diffSeconds = diff/1000;
var HH = Math.floor(diffSeconds/3600);
var MM = Math.floor(diffSeconds%3600)/60;
var formatted = ((HH < 10)?("0" + HH):HH) + ":" + ((MM < 10)?("0" + MM):MM)
getTime(diffSeconds);
}
function getTime(seconds) {
var days = Math.floor(leftover / 86400);
//how many seconds are left
leftover = leftover - (days * 86400);
//how many full hours fits in the amount of leftover seconds
var hours = Math.floor(leftover / 3600);
//how many seconds are left
leftover = leftover - (hours * 3600);
//how many minutes fits in the amount of leftover seconds
var minutes = leftover / 60;
//how many seconds are left
//leftover = leftover - (minutes * 60);
alert(days + ':' + hours + ':' + minutes);
}
alternative modificitaion extended code..
http://jsfiddle.net/vvGPQ/48/
showDiff();
function showDiff(){
var date1 = new Date("2013/01/18 06:59:00");
var date2 = new Date();
//Customise date2 for your required future time
var diff = (date2 - date1)/1000;
var diff = Math.abs(Math.floor(diff));
var years = Math.floor(diff/(365*24*60*60));
var leftSec = diff - years * 365*24*60*60;
var month = Math.floor(leftSec/((365/12)*24*60*60));
var leftSec = leftSec - month * (365/12)*24*60*60;
var days = Math.floor(leftSec/(24*60*60));
var leftSec = leftSec - days * 24*60*60;
var hrs = Math.floor(leftSec/(60*60));
var leftSec = leftSec - hrs * 60*60;
var min = Math.floor(leftSec/(60));
var leftSec = leftSec - min * 60;
document.getElementById("showTime").innerHTML = "You have " + years + " years "+ month + " month " + days + " days " + hrs + " hours " + min + " minutes and " + leftSec + " seconds the life time has passed.";
setTimeout(showDiff,1000);
}
Below code will return the days left from today to futures date.
Dependencies: jQuery and MomentJs.
var getDaysLeft = function (date) {
var today = new Date();
var daysLeftInMilliSec = Math.abs(new Date(moment(today).format('YYYY-MM-DD')) - new Date(date));
var daysLeft = daysLeftInMilliSec / (1000 * 60 * 60 * 24);
return daysLeft;
};
getDaysLeft('YYYY-MM-DD');
<html>
<head>
<script>
function dayDiff()
{
var start = document.getElementById("datepicker").value;
var end= document.getElementById("date_picker").value;
var oneDay = 24*60*60*1000;
var firstDate = new Date(start);
var secondDate = new Date(end);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
document.getElementById("leave").value =diffDays ;
}
</script>
</head>
<body>
<input type="text" name="datepicker"value=""/>
<input type="text" name="date_picker" onclick="function dayDiff()" value=""/>
<input type="text" name="leave" value=""/>
</body>
</html>
this code fills the duration of study years when you input the start date and end date(qualify accured date) of study and check if the duration less than a year if yes the alert a message
take in mind there are three input elements the first txtFromQualifDate and second txtQualifDate and third txtStudyYears
it will show result of number of years with fraction
function getStudyYears()
{
if(document.getElementById('txtFromQualifDate').value != '' && document.getElementById('txtQualifDate').value != '')
{
var d1 = document.getElementById('txtFromQualifDate').value;
var d2 = document.getElementById('txtQualifDate').value;
var one_day=1000*60*60*24;
var x = d1.split("/");
var y = d2.split("/");
var date1=new Date(x[2],(x[1]-1),x[0]);
var date2=new Date(y[2],(y[1]-1),y[0])
var dDays = (date2.getTime()-date1.getTime())/one_day;
if(dDays < 365)
{
alert("the date between start study and graduate must not be less than a year !");
document.getElementById('txtQualifDate').value = "";
document.getElementById('txtStudyYears').value = "";
return ;
}
var dMonths = Math.ceil(dDays / 30);
var dYears = Math.floor(dMonths /12) + "." + dMonths % 12;
document.getElementById('txtStudyYears').value = dYears;
}
}
If you use Date objects and then use the getTime() function for both dates it will give you their respective times since Jan 1, 1970 in a number value. You can then get the difference between these numbers.
If that doesn't help you out, check out the complete documentation: http://www.w3schools.com/jsref/jsref_obj_date.asp
var getDaysLeft = function (date1, date2) {
var daysDiffInMilliSec = Math.abs(new Date(date1) - new Date(date2));
var daysLeft = daysDiffInMilliSec / (1000 * 60 * 60 * 24);
return daysLeft;
};
var date1='2018-05-18';
var date2='2018-05-25';
var dateDiff = getDaysLeft(date1, date2);
console.log(dateDiff);
To get the date difference in milliseconds between two dates:
var diff = Math.abs(date1 - date2);
I'm not sure what you mean by converting the difference back into a date though.
Many answers here are based on a direct subtraction of Date objects like new Date(…) - new Date(…). This is syntactically wrong. Browsers still accept it because of backward compatibility. But modern JS linters will throw at you.
The right way to calculate date differences in milliseconds is new Date(…).getTime() - new Date(…).getTime():
// Time difference between two dates
let diffInMillis = new Date(…).getTime() - new Date(…).getTime()
If you want to calculate the time difference to now, you can just remove the argument from the first Date:
// Time difference between now and some date
let diffInMillis = new Date().getTime() - new Date(…).getTime()
function checkdate() {
var indate = new Date()
indate.setDate(dat)
indate.setMonth(mon - 1)
indate.setFullYear(year)
var one_day = 1000 * 60 * 60 * 24
var diff = Math.ceil((indate.getTime() - now.getTime()) / (one_day))
var str = diff + " days are remaining.."
document.getElementById('print').innerHTML = str.fontcolor('blue')
}
THIS IS WHAT I DID ON MY SYSTEM.
var startTime=("08:00:00").split(":");
var endTime=("16:00:00").split(":");
var HoursInMinutes=((parseInt(endTime[0])*60)+parseInt(endTime[1]))-((parseInt(startTime[0])*60)+parseInt(startTime[1]));
console.log(HoursInMinutes/60);

Categories