How to get time difference between two date time in javascript? - javascript

I want time duration between two date time. I have the start date, start time, end date and end time. Now I have to find the difference between them.
Actually I have tried with this following code, but I got the alert like 'invalidate date'.
function myfunction()
{
var start_dt = '2013-10-29 10:10:00';
var end_dt = '2013-10-30 10:10:00';
var new_st_dt=new Date(start_dt);
var new_end_dt=new Date(end_dt);
alert('new_st_dt:'+new_st_dt);
alert('new_end_dt:'+new_end_dt);
var duration=new_end_dt - new_st_dt;
alert('duration:'+duration);
}
the alert msg like as follows:
new_st_dt:invalid date
new_end_dt: invalid date
duration:NaN
when I run in android simulator I got these alert messages.
Please help me how to get it? How to implement this?

You're passing an invalid ISO date string to that Date() constructor. It needs a form like
YYYY-MM-DDThh:mm:ss
for instance
2013-10-29T10:10:00
So you basically forgot the T to separate date and time. But even if the browser reads in the ISO string now, you would not have an unix timestamp to calculate with. You either can call
Date.parse( '2013-10-29T10:10:00' ); // returns a timestamp
or you need to explicitly parse the Date object, like
var duration=(+new_end_dt) - (+new_st_dt);
Further read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

Try formatting you timestamps as isoformat so javascript recognizes them. (you put a "T" between the date and time). An example: '2013-10-29T10:10:00'

function dateDiff(){
var start_dt = '2013-10-29 10:10:00';
var end_dt = '2013-10-30 10:10:00';
var d1= start_dt ;
d1.split("-");
var d2= end_dt ;
d2.split("-");
var t1 = new Date(d2[0],d2[1],d2[2]);
var t2 = new Date(d1[0],d1[1],d1[2]);
var dif = t1.getTime() - t2.getTime();
var Seconds_from_T1_to_T2 = dif / 1000;
return Math.abs(Seconds_from_T1_to_T2);
}

Related

How to compare dates to make sure Google Apps Script is only sending an alert once a day?

I have a script in a Google Sheet that is sending out an alert if a certain condition is met. I want to trigger the script to run hourly, however, if an alert was already sent out today, I don't want to send out another one (only the next day). What is the best way to achieve this?
I've tried formatting the date several ways, but somehow the only thing working for me so far is getting the year, month and day from the date object as int and comparing them separately.
function sendAlert{
var now = new Date();
var yearNow = now.getYear();
var monthNow = now.getMonth() + 1;
var dayNow = now.getDate();
var sheet = SpreadsheetApp.getActive().getSheetByName('CHANGE_ALERT');
var sentYear = sheet.getRange("R2").getValue();
var sentMonth = sheet.getRange("S2").getValue();
var sentDay = sheet.getRange("T2").getValue();
if (yearNow != sentYear || monthNow != sentMonth || dayNow != sentDay) {
sendEmail();
var sentYear = sheet.getRange("R2").setValue(yearNow);
var sentMonth = sheet.getRange("S2").setValue(monthNow);
var sentDay = sheet.getRange("T2").setValue(dayNow);
else {
Logger.log('Alert was already sent today.');
}
}
I think this solution is definitely not the best approach, but I cannot come up with another that merges the date into one. Only comparing the new Date() doesn't work, since the time of day will not necessarily be the same. If I format the date to YYYY-MM-dd, it should work, but then when I get the date again from the spreadsheet it gets it as a full date with the time again.
Requirement:
Compare dates and send an email if one hasn't been sent already today.
Modified Code:
function sendAlert() {
var sheet = SpreadsheetApp.getActive().getSheetByName('blank');
var cell = sheet.getRange(2,18); //cell R2
var date = new Date();
var alertDate = Utilities.formatDate(cell.getValue(), "GMT+0", "yyyy-MM-dd");
var currentDate = Utilities.formatDate(date, "GMT+0", "yyyy-MM-dd");
if (alertDate !== currentDate) {
sendEmail();
cell.setValue(date);
} else {
Logger.log('Alert was already sent today.');
}
}
As you can see, I've removed all of your year/month/day code and replaced it with Utilities.formatDate(), this allows you to compare the dates in the format you specified in your question. I've also changed the if statement to match this, so now we only need to compare alertDate and currentDate.
References:
Utilities.formatDate()
Class SimpleDateFormat

Date in variable reading as "Invalid Date"

Using the following:
var timestart = $('.thisDiv').data("timestart");
var startDateTime = new Date(timestart);
to collect a date from a php file that is updating by ajax from this:
$TimeStart = date( 'Y,m,d,g,i', $TimeStart );
<div class="thisDiv" data-timestart="<?= $TimeStart ?>"></div>
var timestart = $('.thisDiv').data("timestart");
In console I'm getting the following when logging timestart and startDateTime:
2017,07,24,7,50
Invalid Date
If I paste the date that is output as follows
var startDateTime = new Date(2017,07,24,7,50);
Then it works fine. Any ideas why I'm getting Invalid Date?
Your timestart variable (JavaScript) is just a string. So it's a string 2017,07,24,7,50, and not those elements in order - which can't be used as separate parameters like new Date() expects.
Let's take a look at it!
var startDateTime = new Date(2017,07,24,7,50); // Parameters in order - all OK!
var startDateTime = new Date("2017,07,24,7,50"); // A single string - single parameter, not OK!
You need to return a proper format of dates from PHP with a format that's valid in JavaScript. Per the ECMAScript standard, the valid format that should work across all browsers is YYYY-MM-DDTHH:mm:ss.sssZ (see the reference at the bottom). To define that from PHP, you would need to format it as such
$TimeStart = date('c', $TimeStart);
This would return a format such as 2017-07-24T21:08:32+02:00.
Alternatively, you can use a splat/spread-operator ... and split the string it into elements, which I find as the better approach than above.
var timestart = $('.thisDiv').data("timestart"); // Get the string: "2017,07,24,7,50"
timestart = timestart.split(","); // Split into array
var startDateTime = new Date(...timestart); // Pass as arguments with splat-operator
Spread/splat operator in JavaScript
PHP date() documentation
ECMAScript date string (JavaScript)
You need to convert your date from string format to numbers.
var timestart = $('.thisDiv').data("timestart").split(",").map(Number);
var startDateTime = new Date(...timestart);
console.log(startDateTime)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="thisDiv" data-timestart="2017,07,24,7,50"></div>

JavaScript Date.parse return NaN in Mozilla Browser

Mozilla browser I have tried get my time-stamp in JavaScript like strtotime in php
My Code:
//var start_date = data.result[0].start_date;
var start_date = "2011-01-26 13:51:50";
var d = Date.parse(start_date) / 1000;
console.log(d);
// 1296030110
Above code is working fine in chrome. But not working in the Mozilla Browser. I am getting NaN value. Please help me.
After search in google I find one solution to add T between the date and time. so I have added. I am getting the output but the output is not the same in both browser.
var start_date = "2011-01-26T13:51:50";
var d = Date.parse(start_date) / 1000;
console.log(d);
//Mozilla = 1296030110
//Chrome = 1296044910
Do not parse strings with the Date constructor or Date.parse (they do the same thing), it is extremely unreliable, especially for non–standard strings (and some that are). To parse "2011-01-26 13:51:50" as a local time, use a library or a simple function like:
function parseDateTime(s) {
var b = s.split(/\D/);
return new Date(b[0],b[1]-1,b[2],b[3],b[4],b[5])
}
document.write(parseDateTime("2011-01-26 13:51:50") / 1000);
To include validation an support for missing values adds a bit more code on one more line.
var start_date = "2011-01-26 13:51:50";
var d = Date.now(start_date);
console.log(d);
it will run in mozila
you need not to perform any calculation
it automatically converts into milliseconds.
Try this. I am not sure this result is perfect or not.
var start_date = Date("2011-01-26 13:51:50");
var d = Date.parse(start_date) / 1000;
console.log(d);
//1454478429
Try this its work for all browser
start_date="2011-01-26 13:51:50".replace(" ","T");
start_date = new Date(start_date);
var d = start_date.getTime() / 1000;
this will work
var start_date = "Jan 26,2011 13:51:50 ";
var d = Date.parse(start_date)/1000;
console.log(d);
because
The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognised or contains illegal date values (e.g. 2015-02-31).
The parse() method takes a date string (such as "Dec 25, 1995") and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.

NaN javascript error when calculating between dates with timestamp

I would like to begin by saying i looked at multiple threads in this forum before posting. Wasnt able to find my solution :(
Issue: getting a NaN error when trying to find the difference between two dates with a timestamp from two textboxes.
The date format i'm using is DDMMYYYY HH:MM - 27/01/2015 00:00
code below.
thank you in advance for this super helpful forum :)
function stringToDate(s) {
var dateParts = s.split(' ')[0].split('-');
var timeParts = s.split(' ')[1].split(':');
var d = new Date(dateParts[0], --dateParts[1], dateParts[2]);
d.setHours(timeParts[0], timeParts[1], timeParts[2]);
return d;
}
function test() {
var a = textbox_1.value;
var b = textbox_2.value;
alert(stringToDate(a) - stringToDate(b));
}
Your date has / as separator but you are splitting the string on -. Change
var dateParts = s.split(' ')[0].split('-');
to
var dateParts = s.split(' ')[0].split('/');
Also, your time part has only hours and minutes, so there is no timeParts[2] present, just remove it from the setHours() call. Like this:
d.setHours(timeParts[0], timeParts[1])
Fiddle: http://jsfiddle.net/2evj59d1/
EDIT
Your code returns the difference in milliseconds. To convert it into date format just change
alert(stringToDate(a) - stringToDate(b));
to
alert(new Date(stringToDate(a) - stringToDate(b)));
The code is trying to parse a time in the format HH:MM:SS. Skip the third part:
d.setHours(timeParts[0], timeParts[1]);
You can convert the date into milliseconds, get the difference and get the date back.
Fiddle
JSCode:
var a = new Date();
a.setDate(15);
a = a.getTime();
var b = new Date();
b.setDate(32);
b = b.getTime();
var c = b - a;
var date = new Date(c);
alert(date.getDate() - 1);
for those who may have stumbled upon my post, i found my answer at the link below by user benjour.
How do I get the difference between two Dates in JavaScript?

Save date 'without' time in JavaScript

At the moment I save my date like this: ISODate("2014-11-17T16:19:16.224Z"), but I want this result: ISODate("2014-11-16T23:00:00Z"). How can I do this?
An easier alternative is to use Date.setHours() - in single call you can set what you need - from hours to milliseconds. If you just want to get rid of the time.
var date = new Date();
date.setHours(0,0,0,0);
console.log ( date );
Set the parts you don't want saved to 0. In your example, you would set the minutes, seconds, and milliseconds to 0.
var date = new Date();
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
var isoDateString = date.toISOString();
console.log(isoDateString);
Or, a less verbose option:
var date = new Date();
var isoDateString = date.toISOString().substring(0,10);
console.log(isoDateString);
To Save a date without a time stamp:
let date = new Date().toLocaleDateString('en-US');
console.log(date)
// OUTPUT -> m/d/yyyy
Use this to find options to add as paramaters for the toLocaleDateString function

Categories

Resources