Okay so what i'm trying to do is get the time values between 2 different dates.
For example:
date1 = 3/2/2014 - 14:12
date2 = 4/2/2014 - 16:22
How would I get the time difference between date1 and date2? (26hrs, 10mins) <- that would be the perfect output for what I want.
I've had a look at the parse method and if I understand it correctly, I think I could make that work by doing something like:
myDate = date1;
myDate.parse(date2);
then convert the output to how I wanted it from there, but I haven't seen any examples where it takes the time of day into consideration.
You just need to subtract the two Date object to get the difference since JavaScript will convert it to the right type automatically:
date1 - date2 //difference in milliseconds
For formatting, you can set up a function similar to this:
Number.prototype.format = function(){
return [
(this/86400|0), "days",
(this/3600|0) % 24 , "hours",
(this/60|0) % 60 , "minutes",
(this|0) % 60 , "seconds"
].join(" ");
};
((date1 - date2)/1000).format(); //Formatted string
Demo: http://jsfiddle.net/DerekL/Prb7j/ (Time formatting also included)
You could use the Date class and then just subtract the 2 dates
var difference = ( new Date(2014, 2, 4, 16, 22, 0).getTime()
- new Date(2014, 2, 3, 14, 12, 0).getTime()
) / 1000
getTime() gives you the time in milliseconds, so you have to divide by 1000 to get the result in seconds.
Related
I've seen a lot of functions to convert dates around but couldn't find anything specific on how to convert Days:Hours:Minutes:Seconds to milliseconds.
So here is a basic function I've made to help you guys out. This is useful if you're coding a stopwatch, clock or anything like that.
Normally I've seen this done inline without using a utility function, but if you're going to create a util let's make it extensible.
I disagree with the arguments Array, it's difficult to remember what represents what. Unless you're only doing day/hour/minute/second, this can get confusing. Additionally, unless you're always using every parameter this becomes cumbersome.
It's incorrect for zero values (passing 0 for any value causes it to be incorrect)
const conversionTable = {
seconds: 1000,
minutes: 60*1000,
hours: 60*60*1000,
days: 24*60*60*1000,
};
const convertTime = (opts) =>
Object.keys(opts).reduce((fin, timeKey) => (
fin + opts[timeKey] * conversionTable[timeKey]
), 0)
console.log(convertTime({
days: 5,
hours: 4,
minutes: 2,
seconds: 19,
}));
console.log(convertTime({seconds: 1}));
function convertDhms(d,h,m,s){
d <= 0 ? d=1 : d=d*24*60*60*1000;
h <= 0 ? h=1 : h=h*60*60*1000;
m <= 0 ? m=1 : m=m*60*1000;
s <= 0 ? s=1 : s=s*1000;
return d + h + m + s;
}
Usage:
var finalDate = convertDhms(5, 4, 2, 19); /* will convert 5 days, 4 hours, 2 minutes and 19 seconds to miliseconds. Keep in mind that the limit to hours is 23, minutes 59 and seconds 59. Days have no limits. */
I suppose a simple solution is to use the Date object's parse method, which gives back the milliseconds of the object. The catch is that it's meant to return the time from the UNIX Epoch time.
// see docs for Date constructor
const baseDate = new Date(0,0,0,0,0,0,0);
const baseMS = Date.parse(baseDate);
// base milliseconds is not zero
// it defaults to a day before Jan 1, 1970 in ms
console.log(baseMS);
function convertToMS(dy,hr,mn,s,ms) {
const date = new Date(0,0,dy,hr,mn,s,ms);
const dateMS = Date.parse(date);
return dateMS - baseMS;
}
// one day in milliseconds
console.log(convertToMS(1,0,0,0,0));
console.log(24 * 60 * 60 * 1000);
P.S. I don't quite understand the logic behind why a new Date object with zero in all parameters returns a large negative value, but we have to account for that in the code.
EDIT: Since there's is a discrepancy between the number of days in each month, and days in each year, it's better to not have year and months in the input of the function convertToMS.
I'm a newbie and recently started to read Beginning Javascript, by McPeak and Wilton. The authors propose an exercise about dates calculation. This is the exercise
Using the Date type, calculate the date 12 months from now.
I tried to solve it with this code
//gets today's date
var today = new Date();
//this line transforms the date in milliseconds
var daysAsMilliseconds = 1000* 60 * 60 * 24 * today.getDate();
//creates a new Date object
console.log(new Date(today.setDate(365) + daysAsMilliseconds));
The result I get here is correct(August 11th 2018).
Later, I wonder if it was really necessary to create 2 variables and tried this solution:
var today = new Date();
console.log(new Date(today.setDate(365) + (1000 * 60 * 60 * 24 * today.getDate())));
Here the solution was incorrect. The console showed August 31 2018. Why?
If necessary, here you will find the repl.it with the code
You call setDate, before you call getDate , therefore getDate will always return 365. Simply swapp it:
new Date((1000 * 60 * 60 * 24 * today.getDate()) + today.setDate(365))
Or its may easier to work with months directly:
today.setMonth(today.getMonth() + 12);
var intwelvemonths = today;
All you need to do is add 1 to the year:
var yearFromNow = new Date();
yearFromNow.setYear(yearFromNow.getFullYear() + 1);
Setting the date to 365 makes no sense; .setDate() is for day-of-month, so setting it to that constant moves the date a year (usually) from the last day of the previous month. And you don't need to do any other math outside of the date API; just increment the year, and you're done.
You're calling today.setDate(365) before you're adding the results of today.getDate(): today.getDate() will give the date that you set, not today's date.
Changing the order of operations will do the trick:
var today = new Date();
new Date((1000 * 60 * 60 * 24 * today.getDate()) + today.setDate(365));
I recommend you to use a package as moment.js because it manage a lot of date formats, and it has very good implementations for date managing.
Using moment js for add.
moment().add(Number, String);
Example
var m = moment(new Date(2011, 2, 12, 5, 0, 0));
m.hours(); // 5
m.add(1, 'days').hours(); // 5
For more docs see moment().add() docs
I am using google sheets where there is a duration value of 69:41:00 where it's 69 hours, 41 minutes, 0 secs. There doesn't seem to be a function to convert this to days, hours and minutes so I did some searching and some had suggested a custom function. Not sure exactly how it works but made some changes from the original to fit what I needed. The code below:
/**
* Format Duration to Days,Hours,Minutes
*
* #param {duration} input value.
* #return Days,Hours,Minutes.
* #customfunction
*/
function FormatDuration(duration) {
// Retrieve the hours and minutes
var hrs = duration.getHours();
var days = Math.floor(hrs/24);
var hours = hrs % 24;
var mins = duration.getMinutes();
// Convert the result to a number to use in calculations
var result = days + 'd ' + hours + ' h '+ mins+' min';
return result;
}
The result should be 2d 21h 44 min but instead I got 0d 21 h 35 min. Am I doing something wrong here?
I was going to add, why don't you just use a custom format of
ʺd\d hh\h mm\mʺ ?
This works fine in Excel but not in GS because it uses a different base for dates so duration like 69:41:00 would be interpreted as 1/1/1900 21:41 and the days are not correct. So you would have to break it down into days (whole numbers) and hours+minutes (fractions of a day) like this
=text(int(A1),ʺ#0\d ʺ)&text(mod(A1,1),ʺHH\h MM\mʺ)
You can make it work in Google Scripts if you want to by adjusting the date - should work OK for durations up to 1 month.
The reason for adding 2 to the date is that a time like 03:21:00 (less than a day) is seen as a date - namely 30th December 1899 ! So I add 2 to it to make it 1st January 1900. However, now the day part of the date is 1 and I want it to be zero. So I have to subtract 1 from the day further down.
This strange behaviour is probably why you're advised to do it the other way and work in milliseconds, but I was just interested to see if there was a way of making the original code work.
/**
* Format Duration to Days,Hours,Minutes
*
* #param {duration} input value.
* #return Days,Hours,Minutes.
* #customfunction
*/
function FormatDuration(duration) {
// Add 2 days to the date
var date=new Date(duration.setDate(duration.getDate()+2));
Logger.log(date.getDate());
var hours = duration.getHours();
// Take 1 off the day part of the date
var days = date.getDate()-1;
var mins = duration.getMinutes();
// Convert the result to a number to use in calculations
var result = days + 'd ' + hours + ' h '+ mins+' min';
return result;
}
function(durations){
var timeArr = durations.split(':'); //["69","41","00"]
//your code
}
getHours is a method of object Date.
var t = new Date;
t.getHours();
How do you expect to get more than 24hours from a Date object? It is not the same as what you expect as Duration. Date is for points of time in calendar, so at most you'd get the 23:59:59 of any day. You can get date2 - date1 = milliseconds diff, and work on it, as following;
function FormatDuration(date1, date2) {
var milliseconds = date2 - date1;
var mins = Math.floor((milliseconds / (1000*60)) % 60);
var hours = Math.floor((milliseconds / (1000*60*60)) % 24);
var days = Math.floor(milliseconds / (1000*60*60*24));
var result = days + ' d ' + hours + ' h '+ mins + ' min';
console.log(result);
}
FormatDuration(new Date(2000, 5, 1, 5, 13, 0, 0),
new Date(2000, 5, 2, 15, 31, 0, 0))
You can find more details here
I've been working with DateRangeSlider for a couple of days and now I'm using it as a time slider - fiddle
My problem is that the min time is 02:00 and it needs to be 00:00, and max time is 01:59 instead of 23:59.
If I changed the formatter values from
h = val.getHours(),
m = val.getMinutes();
to
h = val.getUTCHours(),
m = val.getUTCMinutes();
it displays the correct start-end hour but when I'm getting those values:
var values = $("#slider").dateRangeSlider('values');
var test = values.min;
it still gets the other values: 02:00 instead of 00:00.
Is there any way to format the min/max value but when the values are read to display the same hour?
You need to take into account the TimeZone and also the Daylight Saving Time (the Date() object is relied on them).
Your solution can be:
var minDateStr = "2014-01-01T00:00:00Z";
var maxDateStr = "2014-01-01T23:59:00Z";
var min2 = new Date(new Date(minDateStr).getTime() + new Date(minDateStr).getTimezoneOffset() * 60000),
max2 = new Date(new Date(maxDateStr).getTime() + new Date(maxDateStr).getTimezoneOffset() * 60000);
Here is a fix to your jsfiddle:
http://jsfiddle.net/z1govrt7/
I have updated format for date and time as below
var min2 = new Date(2014, 0, 1, 00, 00, 00),
max2 = new Date(2014, 11, 31, 23, 59, 59);
Please check http://jsfiddle.net/LJrYf/149/ fiddle now.
I have updated your code and now its working as expected.
I have 2 dates, that I convert to UNIX timestamp - start date and confirm date. I subtract one from another and get numbers like these:
-12643,
0,
3037,
1509,
-3069
Basically, what I need to do is to get the difference between the two dates in minutes, but I don't know how to convert those to minutes. The end output should be something like: -25, 13, 155
How did you get the original numbers? I believe the standard Unix timestamps are in seconds, so you should be able to divide by 60 to get minutes. However, Date.now() in JavaScript, for example, returns milliseconds, so you'd need to divide by 60,000.
Given two UNIX timestamps: a, b; you can calculate the difference between them in minutes like this:
var a = 1377005400000; //2013-07-20 15:30
var b = 1377783900000; //2013-07-29 15:45
var dateA = new Date(a);
var dateB = new Date(b);
var dayRelativeDifference = dateB.getHours()*60 + dateB.getMinutes()
- dateA.getHours()*60 - dateA.getMinutes();
// dayRelativeDifference will be 15
var absoluteDifference = (b-a)/60
// absoluteDifference will be 12975000
Also have a look at http://www.w3schools.com/jsref/jsref_obj_date.asp
You just need to divide by 60. You already have the difference between the two timestamps, so none of the Date overhead above is necessary:
var diffs = new Array(-12643, 0, 3037, 1509, -3069);
for (var i = 0; i < diffs.length; i++)
document.write(diffs[i] % 60);