How to find the number of days difference using Google Script - javascript

I was trying to find the difference between two days, I'm getting NaN.
function formatDate(oldFormat,duration,timestamp){
var formattedDate = Utilities.formatDate(oldFormat, "IST","yyyy,MM,dd");
Logger.log(timestamp);
var newDate=new Date(timestamp*1000);
Logger.log(newDate);
newDate=Utilities.formatDate(newDate,"IST","yyyy,MM,dd");
Logger.log(formattedDate);
Logger.log(newDate);
var date1=new Date(formattedDate).getTime();
Logger.log(date1)
var date2=new Date(newDate).getTime();
Logger.log(date2)
var diff=daydiff(date2,date1);
Logger.log(diff); }
function daydiff(first, second) {
return (second-first)/(1000*60*60*24);}
How to find the difference between two date in days? I've date in this format :
date 1 : 2015,05,12
date 2: 2015,05,28

There is no point to use Utilities.formatDate() as it is meant to convert a normal date in to any format, not the other way round.
Also not sure what (oldFormat,duration,timestamp) stand for. You do not use duration in your script, and both dates you showed seem to be the same format.
If you are simply trying to find the difference between two dates, try this:
function formatDate(date1,date2){
date1 = new Date(fixDate(date1));
date2 = new Date(fixDate(date2));
var diff = (date2-date1)/(1000*60*60*24);
return(diff);
}
function fixDate(date){
var collector = date;
if (collector.match(",")!=null){
collector = collector.split(",");
var myString = [collector[1], collector[2], collector[0]].join("/");
return myString
}
}

Related

How to subtract two different dates from a date/time stamp?

I need to subtract a date like 1/26/2015 from a date-time like 2016-01-27T01:10:57.569000+00:00. From what I've read converting both to distance in milliseconds from Epoch and then subtracting is the easiest way. I've tried using various methods, but all the methods seem to say 2016-01-27T01:10:57.569000+00:00 is invalid data. The method .getTime() works great for the 1/26/2015 format, but it can't read the 2016-01-27T01:10:57.569000+00:00.
How does one go about getting the date/time UTC time into milliseconds?
On a complicated way you can use a regex to extract each part of the date as string and then use them in a new Date with all parameters:
function getTimeDifference(){
var regEx = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):([\d.]+)/;
var dateString = '2016-01-27T01:10:57.569000+00:00';
var r = regEx.exec( dateString );
var date1 = new Date(r[1], r[2]-1, r[3], r[4], r[5], r[6]); // Notice the -1 in the month
var date2 = new Date('1/26/2015');
var difference = date1 - date2;
Logger.log(difference);
}
I ended up using this. When I call parseDate(), I used getTime() to get the date in milliseconds then subtracted them and converted them to days. For my use case the time didn't have to be down to the second, but if it did, it wouldn't be hard to parse more info from the string. I ran into trouble initially because as a beginner Javascript writer I didn't know why apps script wouldn't accept this format into the date constructor.
function parseDate(str) {
//This should accept 'YYYY-MM-DD' OR '2016-01-27T01:10:57.569000+00:00'
if(str.length == 10){
var mdy = str.split('-');
return new Date(mdy[0], mdy[1]-1, mdy[2]);
}
else
{
var mdy = str.split('-');
var time = mdy[2].split('T');
var hms = time[1].split(':');
return new Date(mdy[0], mdy[1]-1, time[0], hms[0], hms [1]);
}
}
If you are confident that the values in the date strings will always be valid and that the ISO8601 string will always have offset 00:00 (i.e. UTC), then simple parse functions are:
// Parse ISO 8601 format 2016-01-27T01:10:57.569000+00:00
function parseISOUTC(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0],b[1]-1,b[2],b[3],b[4],b[5],b[6]));
}
document.write(parseISOUTC('2016-02-04T00:00:00.000+00:00'));
// Parse US format m/d/y
function parseMDY(s) {
var b = s.split(/\D/);
return new Date(b[2],b[0]-1,b[1]);
}
document.write('<br>'+ parseMDY('2/4/2016'))
document.write('<br>'+ (parseISOUTC('2016-02-04T00:00:00.000+00:00') - parseMDY('2/4/2016')))
Note that the first string is UTC and the second will be treated as local (per ECMAScript 2015), so the difference between 2016-02-04T00:00:00.000+00:00 and 2/4/2016 will be the time zone offset of the host system.

How do I get the time in milliseconds from 2 different string?

I have the following code which I get from parameters in the URL.
This is what I have in the URL
&dateStart=15.01.2015&timeStart=08%3A00&
After getting the parameters I have the following: 15.01.2015:08:00
Using Javascript how can I parse this string to get the date in milliseconds?
Date.parse(15.01.2015:08:00)
But obviously this doesn't work.
Date.parse(15-01-2015)
This works and I can change this but then how do I add or get the milliseconds from the time??
This is quite possibly the ugliest JavaScript function I've written in my life but it should work for you.
function millisecondsFromMyDateTime(dateTime) {
var dayMonth = dateTime.split('.');
var yearHourMinute = dayMonth[2].split(':');
var year = yearHourMinute[0];
var month = parseInt(dayMonth[1]) - 1;
var day = dayMonth[0];
var hour = yearHourMinute[1];
var minute = yearHourMinute[2];
var dateTimeObj = new Date(year, month, day, hour, minute, 0, 0);
return dateTimeObj.getTime();
}
It will work with the format that your DateTime is in aka day.month.year:hours:minutes.
You can achieve it using Javascript Date Object and JavaScript getTime() Method:
var dateString="01.15.2015 08:00";
var d = new Date(dateString);
console.log(d);
var ms=d.getTime();
console.log(ms);
ms+=10000;
console.log(new Date(ms));
Here is a DEMO Fiddle.
Note: Change your date string from 15.01.2015:08:00 to "01.15.2015 08:00" because it's not a valid Date format.
Check for format
Date() in javascript :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Format allowed :
https://www.rfc-editor.org/rfc/rfc2822#page-14
You can try to use moment.js library like this:
moment('15.01.2015 08:00', 'DD.MM.YYYY HH:mm').milliseconds()
Just for the sake of completion, you can always extract the information and create a Date object from the extracted data.
var dateStart = '15.01.2015'
var timeStart = '08:00';
var year = dateStart.substring(6,10);
var month = dateStart.substring(3,5);
var day = dateStart.substring(0,2);
var hour = timeStart.substring(0,2);
var mins = timeStart.substring(3,5);
var fulldate = new Date(year, month-1, day, hour, mins);
console.log(fulldate.getTime());

Parsing a date in JavaScript?

Is there a way I could get the year, month (0 based) and day from '03/05/2013'
If so, how?
Thanks
Is there a safe way to do it that can check if it is in the correct format?
You have the Date.parse method which parses a Date string and returns its timestamp, so you can call new Date().
Something like this:
new Date(Date.parse('03/06/2013'))
Most easy is using the split() function, i think:
var date = "03/05/2013";
var dateParts = date.split("/");
var day = dateParts[0];
var month = dateParts[1];
var year = dateParts[2];
http://jsfiddle.net/s7ma2/1/

JS - Compare which date is older

I want to compare two dates as which is bigger in those dates.
var date1 = 2011-9-2;
var date1 = 2011-17-06;
Can anybody say how can I do this?
You'll need to convert both strings to date objects first.
var date1 = new Date('2011-09-02');//yyyy-mm-dd format
var date2 = new Date('2011-06-17');
if(date1 > date2){
alert('date1 is bigger than date2');
}
Once you have the 2 variables as date objects you can compare them against each other (without needing to convert to milliseconds/minutes/?)
Check this link
And then do something like this:
var days = 0;
var difference = 0;
Christmas = new Date("December 25, 2005");
today = new Date();
difference = Christmas - today;
days = Math.round(difference/(1000*60*60*24));
Code source
Create Date objects from your two values (check this link) and use that to do the comparison.

Javascript get date in format [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 3 years ago.
I want to get today's date in the format of mm-dd-yyyy
I am using var currentDate = new Date();
document.write(currentDate);
I can't figure out how to format it.
I saw the examples var currentTime = new Date(YY, mm, dd); and currentTime.format("mm/dd/YY");
Both of which don't work
I finally got a properly formatted date using
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;//January is 0!`
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm}
var today = mm+'/'+dd+'/'+yyyy;
document.write(today);'`
This seems very complex for such a simple task.
Is there a better way to get today's date in dd/mm/yyyy?
Unfortunately there is no better way, but instead of reinventing the wheel, you could use a library to deal with parsing and formatting dates: Datejs
<plug class="shameless">
Or, if you find format specifiers ugly and hard to decipher, here's a concise formatting implementation that allows you to use human-readable format specifiers (namely, the Date instance getters themselves):
date.format("{Month:2}-{Date:2}-{FullYear}"); // mm-dd-yyyy
</plug>
var today = new Date();
var strDate = 'Y-m-d'
.replace('Y', today.getFullYear())
.replace('m', today.getMonth()+1)
.replace('d', today.getDate());
Simple answer is no. Thats the only way to do it that I know of.
You can probably wrap into a function that you can reuse many times.
date.js is what you need. For example, snippet below is to convert a date to string as Java style
new Date().toString('M/d/yyyy')
function dateNow(splinter){
var set = new Date();
var getDate = set.getDate().toString();
if (getDate.length == 1){ //example if 1 change to 01
getDate = "0"+getDate;
}
var getMonth = (set.getMonth()+1).toString();
if (getMonth.length == 1){
getMonth = "0"+getMonth;
}
var getYear = set.getFullYear().toString();
var dateNow = getMonth +splinter+ getDate +splinter+ getYear; //today
return dateNow;
}
format this function is mm dd yyyy
and the dividing you can choice and replace if you want... for example
dateNow("/") you will get 12/12/2014
There is nothing built in, but consider using this if you are already using jQuery (and if not, then you should consider that as well!)
http://plugins.jquery.com/project/jquery-dateFormat
(new Date()).format("MM-dd-yyyy")
N.B. month is "MM" not "mm"
function appendZeros(value,digits){
var c= 1;
initValue = value;
for(i=0;i<digits-1;i++){
c = c*10;
if( initValue < c ){
value = '0' + value;
}
}
return value;
}

Categories