How to convert string to ISOString? - javascript

I have 3 variables: (1)Date (2) StartTime (3) EndTime
I would like to bring them as two variables (1)Date and StartTime (2) Date and EndTime, so that I can create a google calendar event.
As per my understanding, in order to create a google calendar event I need to pass ISO String format for event timings. Can anyone check the below code and help me with the missing piece.
function createEvent(title,Dt,startTime,endTime,col) {
var calendarId = '_____#group.calendar.google.com';
Logger.log(Dt); //2016-07-21
Logger.log(startTime); // 11:55 AM
Logger.log(typeof(startTime)); //string
//Help Needed to convert + to ISO
var event = {
summary: title,
start: {
dateTime: startISO
},
end: {
dateTime: endISO
},
colorId: col
};
event = Calendar.Events.insert(event, calendarId);
Logger.log('Event ID: ' + event.getId());

You can use .toISOString() on the Date object to get an ISO String, but Google Calendar is requesting a slightly different format than this, but it is a quick fix. Start with a normal conversion:
(new Date()).toISOString(); // "2016-07-29T00:00:00.000Z"
var startTime = new Date();
var isoStartTime = startTime.toISOString();
If you need to make the Date from separate objects you can:
var yourDate = '2016-07-29';
var yourTime = '11:55 AM';
var startTime = new Date(yourDate);
startTime.setHours(yourTime.split(':')[0]); // 11
startTime.setMinutes(yourTime.split(':')[1].substr(0,2)); // 55
startTime = startTime.toISOString(); // "2016-07-29T11:55:00.000Z"
Then change it to what Google's looking for:
// To RFC 3339...
startTime.substr(0,startTime.length-5)+'Z'; // "2016-07-29T11:55:00Z"
Or
//if the "startTime = startTime.toISOString()" assignment happened
startTime.split('.')[0]+'Z';
//if startTime is a Date object, not a string
startTime.toISOString().split('.')[0]+'Z';
You can also (and probably preferrably) use numbers instead of strings for all that; if you pass hours and minutes separately it could look cleaner than that string operation:
var startTime = new Date(yourDate);
startTime.setHours(yourHours); // string or int
startTime.setMinutes(yourMinutes); // string or int

Related

How to use intervalToDuration function from date-fns

I tried using the intervalToDuration function from date-fns but I keep getting an error that says End Date is invalid.
My code is as follows
import { intervalToDuration} from "date-fns";
remaining() {
const now = new Date();
const end = this.endDate;
return intervalToDuration({
start: now,
end: end,
});
},
this.endDate is dynamically populated but for this question is equal to 2021-02-26T00:00:00.000Z
Since your endDate variable is coming from an API, it is being stored as a string, not a date.
Calling intervalToDuration is expecting an interval object to be passed as the parameter. An interval consists of two Dates or Numbers (unix timestamp)
To correct this, you must convert endDate to a date object, below is an untested example;
const remaining = () => {
const endDate = "2021-02-26T00:00:00.000Z";
const now = new Date();
const end = new Date(endDate);
return intervalToDuration({
start: now,
end: end
});
};
const dur = remaining();
console.log("DURRATON ", JSON.stringify(dur));
//
// Response == DURRATON {"years":0,"months":1,"days":8,"hours":15,"minutes":42,"seconds":0}
//
Notice : This does not handle timezones correctly. new Date() will create a datetime in the client timezone where it appears that your response from the API is in GMT timezone

How can I get a string date in the format "2016-07-06T10:57Z" from Date() and toISOString

I need to get a date in this format:
2016-07-06T10:57Z
Using this code I have been able to get a date in a format somewhat like I need:
var isoDate = new Date().toISOString();
2016-07-06T08:46:08.127Z
But is there a way I can remove the seconds and fraction of seconds from the date so it appears exactly like the date: "2016-07-06T10:57Z" ?
You will always want to remove the last 8 characters ('Z' included) thus you can use a function like slice
isoDate = isoDate.slice(0, -8); //Remove seconds + fractions + Z
isoDate += "Z"; //Add back the Z
You can use this way because the format returned by toISOString() will always be
YYYY-MM-DDTHH:mm:ss.sssZ
Please try
var isoDate = new Date().toISOString();
var pos = isoDate.lastIndexOf(':');
var datePart1 = isoDate.substring(0,pos);
var datePart2 = isoDate.substr(-1, 1);
var dateStr = datePart1+datePart2;
console.log(dateStr);

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 to find the number of days difference using Google Script

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
}
}

Javascript : date automatically increments by +1 value (Convert String to Date object)

I use Date() function to convert string to date object . The problem is , If i give Date("April , 31 ,2012") it will take it as May , 01 , 2012 (for the rest of the days its working) Please check my approach is correct from the code below.
function TestDate(objValue,strError){
var ret=true;
var frmdate=objValue.value;
var datesplit=frmdate.split("-");
var y =datesplit[0];
var m=datesplit[1];
var d=datesplit[2];
var testdate;
// Create date object using given input data
testdate = new Date(m+"/"+d+"/"+y);
alert("Created date"+testdate.toString());
var td=testdate.getDate();
var tm=testdate.getMonth()+1;
var ty =testdate.getFullYear();
alert(d+"="+td);
alert(m+"="+tm);
alert(y+"="+ty);
var valid=((d==td) && (m==tm) && (y==ty));
alert(valid);
if(valid == false)
{
ret =false;
}
return ret;
}
As sayed by #ajreal in comments, April has only 30 days.
The internal date object increments the month to have a valid date.
The code:
testdate = new Date(m+"/"+d+"/"+y);
is depends on non-standard, implementation specific parsing of the string. Far better to use the data you started with to create a date unambiguously:
testdate = new Date(y, m - 1, d);
As for validating a date, a simple function using an ISO8601 compliant date of format yyyy-mm-dd is:
function validateDate(dateString) {
var bits = dateString.split('-');
var date = new Date(bits[0], bits[1] - 1, bits[2]);
return date && date.getFullYear() == bits[0] && date.getDate() == bits[2];
}
That way if the string passed to the function is turned into a date, you can check that the date so created matches the input. If not, it wasn't valid and the function returns false. It also returns false if the string doesn't get turned into a date.

Categories