Google forms to calendar event issues with date format - javascript

So I have a very simple form that takes 3 inputs, a title, start and end date. I have tried to use a simple script to produce a calendar event. this can be seen below.
function onFormSubmit(e) {
var title = e.values[1];
var start_time = new Date(e.values[2]);
var end_time = new Date(e.values[3]);
CalendarApp.createEvent(title, start_time, end_time);
}
The issue I have is that as the date string is UK format (e.g. 05/12/2016 12:00:00) it is logging the events as 12th May as opposed to 5th December.
I am new to all of this so am looking for an elegant and simple solution I understand, not just to copy code I don't.
Thanks.

function convertUKDateToUSDate(date) {
const arr = date.split('/');
const temp = arr[0];
arr[0] = arr[1];
arr[1] = temp;
return arr.join('/');
}
will convert a date string with the prefix "DD/MM/" into "MM/DD/YYYY" format. Split turns the string into an array like ["DD", "MM", "YYYY HH:MM:SS"] and then the temporary variable is used to swap the "MM" and "DD" before the array entries are joined back together with the same character that was used to split them. You'll end up with a final onFormSubmit(e) like this:
function onFormSubmit(e) {
var title = e.values[1];
var start_time = new Date(convertUKDateToUSDate(e.values[2]));
var end_time = new Date(convertUKDateToUSDate(e.values[3]));
CalendarApp.createEvent(title, start_time, end_time);
}
Obviously I'm assuming e.values[2] and e.values[3] are strings. If they're Date objects already (or if you just want a shorter solution), then consider using the Moment.js (the premier Date object library) format function to convert between the formats. Normally I'd recommend using Moment anyways but you said you wanted something you could understand instead of copy.

Related

How to get difference in dates between to dates in JavaScript

I have a split string lines="Ram Hue, 134, 20.5.1994, 20.4.2004"
and I want to get the difference in dates between to dates 20.5.1994 and 20.5.1994, I tried in JavScript but i'ts not working. Also when trying to extract both dates using
lines[2] lines[3] I'm getting wrong outputs
var date1 = new Date(lines[2])
var date2 = new Date(lines[3])
var diffDays = parseInt((date2-date1)/(1000*60*60*24),10)
console.log(diffDays)
Since lines is a string, lines[2] will just get you the character with index 2 within the string. Instead you need to split the string before:
const arr = lines.split(',');
Then you can access both date strings as arr[2] and arr[3]

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>

Google Form on Submit get values and format the time

I am using Google Apps Script with a Google form. When the user submits the Google Form I get a value from a question. I then take that value and make it a date object, from what I saw on this post about daylight savings I use that to determine the timezone. I run the date object through Utilities.formatDate and want to get the correctly formatted date.
example: 9:00 AM
But instead I am getting a completely different time than expected.
My question is: Can someone help me understand why the below code is outputting a time that is 3 hours different?
function onSubmit(e) {
var values = e.values;
Logger.log(values);
try {
var start1 = new Date(values[3]);
var startN = new Date(start1).toString().substr(25,6)+"00";
var startT = Utilities.formatDate(start1, startN, "h:mm a");
Logger.log(startT);
} catch(error) {
Logger.log(error);
}
}
The assumption that Utilities formatDate does not support GMT... parameter is not true.
The post you mentioned in reference is used to get calendar events and is a useful way to get the right value when you get events from another daylight saving period (getting the TZ info from the calendar event itself), for example events for next month will be in "summer time" while we are still in "winter time"...
Your issue might come from different sources depending on time zone settings of your script vs timezone of the source. Could you describe the exact configuration in which you use this script ?
In the mean time, here is a small code that demonstrates how the code is working + the logger results :
function testOnSubmit() {
var eventInfo = {};
var values = {};
values['3'] = new Date();
eventInfo['values'] = values;
Logger.log('eventInfo = '+JSON.stringify(eventInfo)+'\n\n');
onSubmit(eventInfo);
}
function onSubmit(e) {
var values = e.values;
try {
var start1 = new Date(values[3]);
Logger.log('onSubmit log results : \n');
Logger.log('start1 = '+start1)
var startN = new Date(start1).toString().substr(25,6)+"00";
Logger.log('startN = '+startN);
var startT = Utilities.formatDate(start1, startN, "h:mm a");
Logger.log('result in timeZone = '+startT);
} catch(error) {
Logger.log(error);
}
}
EDIT : additionally, about the 30 and 45' offset, this can easily be solved by changing the substring length like this :
var startN = new Date(start1).toString().substr(25,8);
the result is the same, I had to use the other version a couple of years ago because Google changed the Utilities.formatDate method at some moment (issue 2204) but this has been fixed.
EDIT 2 : on the same subject, both methods actually return the same result, the GMT string has only the advantage that you don't have to know the exact timezone name... there is also the Session.getScriptTimeZone() method. Below is a demo script that shows the resulst for 2 dates in January and July along with the log results :
function testOnSubmit() {
var eventInfo = {};
var values = {};
values['3'] = new Date(2014,0,1,8,0,0,0);
eventInfo['values'] = values;
Logger.log('eventInfo = '+JSON.stringify(eventInfo)+'\n\n');
onSubmit(eventInfo);
values['3'] = new Date(2014,6,1,8,0,0,0);
eventInfo['values'] = values;
Logger.log('eventInfo = '+JSON.stringify(eventInfo)+'\n');
onSubmit(eventInfo);
}
function onSubmit(e) {
var values = e.values;
var start1 = new Date(values[3]);
Logger.log('onSubmit log results : ');
Logger.log('start1 = '+start1)
var startN = new Date(start1).toString().substr(25,8);
Logger.log('startN = '+startN);
Logger.log('result in timeZone using GMT string = '+Utilities.formatDate(start1, startN, "MMM,d h:mm a"));
Logger.log('result in timeZone using Joda.org string = '+Utilities.formatDate(start1, 'Europe/Brussels', "MMM,d h:mm a"));
Logger.log('result in timeZone using Session.getScriptTimeZone() = '+Utilities.formatDate(start1, Session.getScriptTimeZone(), "MMM,d h:mm a")+'\n');
}
Note also that the Logger has its own way to show the date object value ! it uses ISO 8601 time format which is UTC value.
Try this instead:
var timeZone = Session.getScriptTimeZone();
var startT = Utilities.formatDate(start1, timeZone, "h:mm a");
The Utilities.formatDate function expects a time zone that is a valid IANA time zone (such as America/Los_Angeles), not a GMT offset like GMT+0700.
I am making the assumption that Session.getScriptTimeZone() returns the appropriate zone. If not, then you might need to hard-code a specific zone, or use a different function to determine it.
Additionally, the +"00" in the script you had was assuming that all time zones use whole-hour offsets. In reality, there are several that have 30-minute or 45-minute offsets.

How to compare string dates?

I have Dates coming back as a string and I'm displaying that on the Front End, how can I compare the dates to see which is earlier...these are just string not date objects
string one = "3/11/12"
string two = "3/13/12"
I know if they were date objects i could do getTime(). Not in this case.
You already answered the problem yourself in the question:
I know if they were date objects i could do getTime()
You can:
var stringOne = "3/11/12",
stringTwo = "3/13/12",
dateOne = new Date(stringOne),
dateTwo = new Date(stringTwo);
if (dateOne.getTime() !== dateTwo.getTime())
console.log("Not the same...");
else
console.log("The same...");
You can convert strings to date objects;
var myDate = new Date("2012/3/13");
With that you could make the normal date operations that you want.

Javascript convert dates

I am getting this "20131218" date/time value from an API result.
What I want to do is convert this date into something like this "2013-12-18". I know this is very easy in PHP by simply doing this code:
echo date("Y-m-d",strtotime('20131218'));
output: 2013-12-18
This is what I tried in javascript:
var myDate = new Date("20131218");
console.log(myDate);
But the output is Date{ Invalid Date } so obviously this is wrong.
My question here what is the equivalent of strtotime in javascript? or if there's no equivalent, how would I convert this value as my expected result(2013-12-18) using javascript?
Your help will be greatly appreciated!
Thanks! :)
The value is invalid to convert it to date. So either from your PHP code send it as a proper format like 20131218
Or convert the value you get in your Javascript to similar kind of format.
var dateVal="20131218";
/*
// If it's number ******* //
var numdate=20131218;
var dateVal=numdate.toString();
*/
var year=dateVal.substring(0,4);
var mnth=dateVal.substring(4,6);
var day=dateVal.substring(6,8);
var dateString=year+"-"+mnth+"-"+day;
var actualDate = new Date(dateString);
alert(actualDate);
JSFIDDLE DEMO
Javascript has a Date.parse method but the string you have is not suitable to pass to it. You don't really need to create a date object just to format a string. Consider:
function formatDateStr(s) {
s = s.match(/\d\d/g);
return s[0] + s[1] + '-' + s[2] + '-' + s[3];
}
alert(formatDateStr('20131218')); // '2013-12-18'
If you wish to convert it to a date object, then:
function parseDateStr(s) {
s = s.match(/\d\d/g);
return new Date(s[0] + s[1], --s[2], s[3]);
}
The reason why it is showing Invalid date is, it wants it to be in format
Following format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS
If you breakdown your string using following format just add dash at relevant places then you are good to go and use newDate.
1. var myDate = new Date("2013-12-18");
alert(myDate);
2. var myDate = new Date(2013,12,18);
Eventually you can modify your string manipulate it and use it in aforementioned format.

Categories

Resources