calculate difference between two timestamp and get difference in unix timestamp - javascript

I want to calculate the difference between two dateTime, one date is submitted by user and other is current time:
user submitted time - now = difference in unix
user submitted time format is:
2014-03-26 10:52:00
Thanks for your help.

You can simply do this with getTime() which returns the number of milliseconds.
var ds = "2014-03-26 10:52:00";
var newDate = new Date(ds).getTime(); //convert string date to Date object
var currentDate = new Date().getTime();
var diff = currentDate-newDate;
console.log(diff);
Sometimes there are chance for cross browser compatibility in parsing the date string so it is better to parse it like
var ds = "2014-03-26 10:52:00";
var dateArray = ds.split(" "); // split the date and time
var ds1 = dateArray[0].split("-"); // split each parts in date
var ds2 = dateArray[1].split(":"); // split each parts in time
var newDate = new Date(ds1[0], (+ds1[1] - 1), ds1[2], ds2[0], ds2[1], ds2[2]).getTime(); //parse it
var currentDate = new Date().getTime();
var diff = currentDate - newDate;
console.log(diff); //timestamp difference

You can use MomentJS library
var user_submited_time = moment('2014-03-26 10:52:00');
var now = moment();
var value = user_submited_time - now;

Related

How to get the exact quantity of months between two dates?

I'm trying to get the quantity of months between two dates
but for some reason, the moment diff method some times returns the correct number and some times is wrong (by one month), (depending on the dates I guess)
var estDate = "some date"; //2022-06-02
estDate = estDate.toString();
var estDateYear = estDate.substring(0,4);
var estDateMonth = estDate.substring(4, 6);
var estDateDay = estDate.substring(6, 8);
estDate = estDateYear + '-' + estDateMonth + '-' + estDateDay;
//first date
estDate = moment(estDate);
//actual date
var date = moment();
//DIFF
var diff= date.diff(estDate, 'month');
diff= diff.toString();
Any Idea why this happens?
You should set the third argument in the diff method to true. This will return fractions of a month instead of a whole number. Then, you can round as needed to return the number you would like.
var diff = Math.floor(date.diff(estDate, 'month', true));
Documentation
https://momentjs.com/docs/#/displaying/difference/
By default, moment#diff will truncate the result to zero decimal places, returning an integer. If you want a floating point number, pass true as the third argument.
Why not just parse the estDate string using moment to begin with?
var estDate = "2022-06-02"; //2022-06-02
estDate = moment(estDate, "YYYY-MM-DD");
//actual date
var date = moment();
//DIFF
var diff= date.diff(estDate, 'month');
diff= diff.toString();
// Simply use Momentjs Formation library
//let estDate = "2022-06-02";
let estDate = moment("2022-06-02", "YYYY-MM-DD");
let actualdate = moment();
let diff= actualdate.diff(estDate, 'M');
diff= diff.toString();
console.log(diff);
<div>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
</div>

Calculate ISO time difference in momentjs

First, I refer :
Get the time difference between two datetimes
Then, it doesn't work as I'm using iso time format.
var now = '2014-12-12T09:30:00.0000000Z';
var then = '2014-12-12T11:00:00.0000000Z';
var timeDuration = moment.utc(moment(now)).diff(moment(then)).format("HH:mm:ss");
Try this:
var format = "YYYY-MM-DD HH:mm Z";
var now = '2014-12-12T09:30:00.0000000Z';
var then = '2014-12-12T11:00:00.0000000Z';
var timeDuration = moment(moment.utc(moment(then, format)).diff(moment(now, format))).format("HH:mm:ss");
print(timeDuration);
"01:30:00"

Convert UTC to local time Javascript

I'm trying to convert UTC time to local time, but the below code is not working. What's wrong in it?
var parsedStartDateTime =
new Date(moment.unix(parseInt(data['StartDateTime'].substr(6)) / 1000));
var startDateTimeMoment =
moment.tz(parsedStartDateTime, tzName);
var formatted_date =
startDateTimeMoment.format("MMM DD YYYY h:mm:ss A");
To format your date try this:
var d = new Date();
var formatD = d.toLocaleFormat("%d.%m.%Y %H:%M (%a)");
Reference: Javascript to convert UTC to local time
Try appending UTC to the string before converting it to a date then use toString() method of date.
Example:
var myDate = new Date('7/1/2014 5:22:55 PM UTC');
date.toString(); //this should give you local date and time
This code was taken from here
Here is my solution:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
var date = convertUTCDateToLocalDate(new Date(date_string_you_received));
date.toLocaleString().replace(/GMT.*/g,"");

Time from X not working as expected moment.js

$.each(data[i].replies, function(m, n) {
var currentdate = new Date();
console.log(n.entry.date_entered);
check = moment(n.entry.date_entered, 'YYYY/MM/DD');
check1 = moment(currentdate, 'YYYY/MM/DD');
console.log(check);
console.log(check1);
var month = check.format('M');
var day = check.format('DD');
var year = check.format('YYYY');
var month1 = check1.format('M');
var day1 = check1.format('DD');
var year1 = check1.format('YYYY');
get = moment([year, month, day]);
get1 = moment([year1, month1, day1]);
g = get1.from(get);
});
Sample n.entry.date_entered : 2014-07-28 12:23:43
For all the dates i am getting a few seconds ago don't know why
I think your problem is the format mask that you pass in to moment.
In your sample you use - as the delimiter but in your format mask you use /. This way moment will not be able to parse the date and will give you the current date instead.
Try changing your format mask to "YYYY-MM-DD".

Calculate difference between two calendar dates in javascript

I need to calculate difference between two calendar dates. I have gone through various posts but the value returned is not correct.
Heres' my code:-
function getTotalDays()
{
var date11 = document.getElementById("departure_date").value;
var date22 = document.getElementById("arrival_date").value;
var one_day=1000*60*60*24;
var date1 = new Date(date11);
var date2 = new Date(date22);
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
// Convert back to days and return
var diffDays = Math.round(difference_ms/one_day);
alert(diffDays);
}
suppse the difference is 2 days its showing as 59.
What's wrong..??
The values you are passing to the date object are likely wrong. Its probably easier for you to do something like this:
var date1 = getDate(date11);
var date2 = getDate(date22);
with getDate being:
function getDate(date) {
//date format dd/mm/yyyy
var dateArr = date.split('/');
var date = new Date(dateArr[2], dateArr[1], dateArr[0]);
return date;
}

Categories