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);
Related
If I have two values, each representing a date such as YYYYMMDDHHMM (YearMonthDayHourMinute) like:
202012141800
202012141614
What I was trying to convey in the question is that this gives me 186 minutes, but this isn't accurate, however, since the last two digits will never be larger than 59 given 60 minutes in an hour. The 100 in 186 comes from hours 18 (6pm) and 16 (4pm).
How can I subtract these in Javascript to account for the extra 40 minutes tacked on if the two timestamps are more than an hour apart?
I have this, but it's not that efficient since I'd need to know the maximum number of hours two timestamps could be apart:
var end_time = $('#the-agenda li.current time').data('end-time'),
time_now = current_display_number,
timer_duration = end_time - time_now;
if (timer_duration > 200) {
// if more than 2 hours, subtract 80 minutes
timer_duration = timer_duration - 80;
}
else if (timer_duration > 100) {
// if more than 1 hour, subtract 40 minutes
timer_duration = timer_duration - 40;
}
I feel like the answer may somehow be in this question's answer, but I am not sure how to apply that parseInt to this situation.
You wouldn't use parseInt. You would use Date.parse, except that the string has to be in a predefined format. Without using a specialized library, you'll have to parse the parts yourself and then create a new Date with the parts. Fortunately though the incoming strings seem straightforward to parse. Do something like this:
let startTimeStr = '202012141614';
let endTimeStr = '202012141800';
let asDateTime = (d) => new Date(
d.substring(0,4),
d.substring(4,6) - 1,
d.substring(6,8),
d.substring(8,10),
d.substring(10,12)
)
let startTime = asDateTime(startTimeStr);
let endTime = asDateTime(endTimeStr);
let result = (endTime - startTime) / 60000;
console.log(result);
// Different in milliseconds
const difference = (new Date('2020-12-14T18:00:00')) - (new Date('2020-12-14T16:14:00'));
const inMinutes = Math.floor(difference / 60000);
You need to convert the string formats to a date object to get accurate date info.
I have a function that returns timezone offset strings (like "+03:00")
And I want to convert this string to minutes offset("+03:00" should turn to 180) using moment.js or built-in plain javascript options
How can I do that?
I've found the solution:
moment().utcOffset("+03:00").utcOffset() // returns 180
moment().utcOffset("-09:00").utcOffset() // returns -540
Using vanilla JS you get the minutes using the below and it will honour positive and negative offsets.
let offset = '-03:30';
let [h, m] = offset.split(':');
let hours = Number.parseInt(h);
let minutes = Number.parseInt(m);
let totalMinutes = hours * 60 + (hours < 0 ? (-minutes) : minutes);
Just get the offset hour and then multiply it by 60 like below:
function parseOffset(offset){
var minutesOffset = (parseInt(offset[1] + offset[2]) * 60)
console.log(parseInt(offset[0] + minutesOffset.toString()))
}
parseOffset("+03:00");
parseOffset("-02:00");
The above returns negative offset too.
The only way to get minutes from the date object in plain javascript is by using
.getTimezoneOffset() - but that doesn't seem to be the case based on your question.
There is no other way that I'm aware of to parse "+03:00" to minutes.
You can try to use Parse Offset method of momentjs timezone.
Usage:
var zone = moment.tz.zone('America/New_York');
zone.parse(Date.UTC(2012, 2, 19, 8, 30)); // 240
I am having a problem with creating an error message on a page where there is a "from date:", and a "to date:". If the difference between the two dates is greater than or equal to 60 days, I have to put up an error message.
I am trying to use moment.js and this is what my code is looking like now. It was recommended that I use it in knockout validation code. this is what it looks like right now:
var greaterThan60 = (moment().subtract('days', 60) === true) ? "The max range for from/to date is 60 days." : null;
I am still not sure how to make it greater than 60 days, not just equal to 60 days. This is what my boss gave me to help.
Reference site for moment().subtract
moment.js provides a diff() method to find difference between dates. please check below example.
var fromDate = 20180606;
var toDate = 20180406;
var dif = moment(fromDate, 'YYYYMMDD').diff(moment(toDate, 'YYYYMMDD'),'days')
console.log(dif) // 61
subtract returns a new moment object. So checking for true always returns false. You can use range and diff to calculate a diff in days and check that:
let start = moment('2016-02-27');
let end = moment('2016-03-02');
let range = moment.range(start, end);
let days = range.diff('days');
let error = null;
if (days > 60) {
error = "The max range for from/to date is 60 days.";
}
You Can try this.
var date = Date.parse("2018-04-04 00:00:00");
var selectedFromDate = new Date(date);
var todayDate = new Date();
var timedifference = Math.abs(todayDate.getTime() - selectedFromDate.getTime());
var daysDifference = Math.ceil(timedifference/(1000 * 3600 * 24));
just use if else loop for greater than 60 days validation.
if(daysDifference > 60)
{
alert("From Date should be less than 2 months");
}
Use the .isSameOrAfter function to compare if the end value is greater than or equal to the start value plus sixty days. Example:
var greaterThan60 = toDate.isSameOrAfter(startDate.add(60, 'days'));
where toDate is your end time as a moment object and startDate is the start time as a moment object. If the end date is greater than or equal to 60 days after the start date, greaterThan60 will be true.
References:
isSameOrAfter
add
I have a mySQL database in which I store the time in this format automatically:
2015-08-17 21:31:06
I am able to retrieve this time stamp from my database and bring it into javascript. I want to then get the current date time in javascript and determine how many days are between the current date time and the date time I pulled from the database.
I found this function when researching how to get the current date time in javascript:
Date();
But it seems to return the date in this format:
Tue Aug 18 2015 10:49:06 GMT-0700 (Pacific Daylight Time)
There has to be an easier way of doing this other than going character by character and picking it out from both?
You can build a new date in javascript by passing the data you receive from your backend as the first argument.
You have to make sure that the format is an accepted one. In your case we need to replace the space with a T. You may also be able to change the format from the back end.
Some good examples are available in the MDN docs.
var d = new Date("2015-08-17T21:31:06");
console.log(d.getMonth());
To calculate the difference in days you could do something like this:
var now = new Date();
var then = new Date("2015-08-15T21:31:06");
console.log((now - then)/1000/60/60/24);
You can select the difference directly in your query:
SELECT DATEDIFF(now(), myDateCol) FROM myTable;
the Date object has a function called getTime(), which will give you the current timestamp in milliseconds. You can then get the diff and convert to days by dividing by (1000 * 3600 * 24)
e.g.
var date1 = new Date()
var date2 = new Date()
var diffInMs = date2.getTime() - date1.getTime()
var diffInDays = diffInMs/(1000*3600*24)
Since none of the other answer got it quite right:
var pieces = "2015-08-17 21:31:06".split(' ');
var date = pieces[0].split('-');
var time = pieces[1].split(':');
var yr = date[0], mon = date[1], day = date[2];
var hour = time[0], min = time[1], sec = time[2];
var dateObj = new Date(yr, mon, day, hr, min, sec);
//if you want the fractional part, omit the call to Math.floor()
var diff = Math.floor((Date.now() - dateObj.getTime()) / (1000 * 60 * 60 * 24));
Note that none of this deals with the timezone difference between the browser and whatever you have stored in the DB. Here's an offset example:
var tzOff = new Date().getTimezoneOffset() * 60 * 1000; //in ms
On Unix, I can run date '+%s' to get the amount of seconds since epoch. But I need to query that in a browser front-end, not back-end.
Is there a way to find out seconds since Epoch in JavaScript?
var seconds = new Date() / 1000;
Or, for a less hacky version:
var d = new Date();
var seconds = d.getTime() / 1000;
Don't forget to Math.floor() or Math.round() to round to nearest whole number or you might get a very odd decimal that you don't want:
var d = new Date();
var seconds = Math.round(d.getTime() / 1000);
Try this:
new Date().getTime() / 1000
You might want to use Math.floor() or Math.round() to cut milliseconds fraction.
You wanted seconds since epoch
function seconds_since_epoch(){ return Math.floor( Date.now() / 1000 ) }
example use
foo = seconds_since_epoch();
The above solutions use instance properties. Another way is to use the class property Date.now:
var time_in_millis = Date.now();
var time_in_seconds = time_in_millis / 1000;
If you want time_in_seconds to be an integer you have 2 options:
a. If you want to be consistent with C style truncation:
time_in_seconds_int = time_in_seconds >= 0 ?
Math.floor(time_in_seconds) : Math.ceil(time_in_seconds);
b. If you want to just have the mathematical definition of integer division to hold, just take the floor. (Python's integer division does this).
time_in_seconds_int = Math.floor(time_in_seconds);
If you want only seconds as a whole number without the decimals representing milliseconds still attached, use this:
var seconds = Math.floor(new Date() / 1000);
You can create a Date object (which will have the current time in it) and then call getTime() to get the ms since epoch.
var ms = new Date().getTime();
If you want seconds, then divide it by 1000:
var sec = new Date().getTime() / 1000;
My preferred way:
var msEpoch = (+new Date());
var sEpoch = (+new Date()) / 1000;
For more information on the + jump down the rabbit hole.
The most simple version:
Math.floor(Date.now() / 1000)
EPOCH means time from 01 January 1970
var date = new Date();
Following line will return the number of milliseconds from 01 Jaunary 1970
var ms = date.getTime();
Following line will convert milliseconds to seconds
var seconds = Math.floor(ms/1000);
console.log("Seconds since epoch =",seconds);
In chrome you can open the console with F12 and test the following code:
var date = new Date().getTime()
console.debug('date: ' + date);
if (Date.now() < date)
console.debug('ko');
else
console.debug('ok');
https://www.eovao.com/en/a/javascript%20date/1/how-to-obtain-current-date-in-milliseconds-by-javascript-(epoch)