Google sheet / javascript not evaluating dates as expected - javascript

I have a PHP script that records a timestamp in a Google Sheet. When I tried to see if this timestamp is between two other timestamps that I have entered manually into the same sheet, I discovered some odd behavior. I thought it might be because Google added a ' at the start of the string in the cell so I tried doing a substr to remove the apostrophe.
function weirdDate(dateFromPhp) {
var dateSubStr = new Date(dateFromPhp.substr(1));
var dateDefault = new Date(dateFromPhp);
return "dateFromPhp: " + dateFromPhp + " dateSubStr: " + dateSubStr + " dateDefault: " + dateDefault;
}
Output is:
dateFromPhp: 16/01/2020 08:33:45
dateSubStr: Mon Jun 01 2020 08:33:45 GMT+1000 (AEST)
dateDefault: Thu Apr 01 2021 08:33:45 GMT+1100 (AEDT)
I have no idea why these dates are months or years away from the expected and with different timezones. The operation without the substr resulted in the correct timezone for me.
Any idea how I can make this string into a timestamp with the correct date?

I discovered the answer. I had no idea javascript expected mm/dd/yyyy as the order for the date format.
function weirdDate(dateFromPhp) {
var dateSubStr = new Date(dateFromPhp.substr(1));
var dateDefault = new Date(dateFromPhp);
var dateUs = americanizeDate(dateFromPhp);
return "dateFromPhp: " + dateFromPhp + " dateSubStr: " + dateSubStr + " dateDefault: " + dateDefault + " dateUS: " + dateUs;
}
function americanizeDate(ausDate) {
var dateParts = ausDate.split("/");
// month is 0-based, that's why we need dataParts[1] - 1
var usDate = new Date(dateParts[1]+"/"+dateParts[0]+"/"+ dateParts[2]);
return usDate;
}
Switching the month and the day solved the problem.

Related

Format dates in Javascript

I have to log my error with datetime in some file, for that I am using following code:
var dLogDate = new Date();
console.log(dLogDate.toString().substring(4) + ', ' + dLogDate.toGMTString().substring(4));
as per above code output comes as follows which is nice but not formated as I need:
"Oct 10 2014 12:48:59 GMT+0530 (IST), 10 Oct 2014 07:18:59 GMT"
I want result s follows :
"10 Oct 2014 12:48:59 (IST), 10 Oct 2014 07:18:59 (GMT)"
see date part before ",". I need 10 Oct instated of Oct 10
This can be done with some function which is substring first 4 character from string and concat at 3rd position again, But I am still curious to know if there are any other simple way to do this? I don't want to use any third party library/script.
Thanks.
You could try adding to the prototype an extension method toISTString
function pad(n) {
return (n < 10) ? '0' + n : n;
}
Date.prototype.toISTString = function(locale) {
var year = this.getFullYear().toString();
var month = this.toLocaleString(locale, { month: "short" }) // ECMAScript Internationalization API, which is very new only available in Blink browsers (Chrome and Opera), IE11, and Firefox 29+.
var day = this.getDate().toString();
var hrs = this.getHours().toString();
var mins = this.getMinutes().toString();
var secs = this.getSeconds().toString();
return day + " " + month + " " + year + " " + pad(hrs) + ":" + pad(mins) + ":" + secs + " (IST)";
};
dLogDate = new Date();
console.log(dLogDate.toISTString("en-us") + ', ' + dLogDate.toGMTString().substring(4));
JSFiddle
You can use date functions to format date
http://www.w3schools.com/jsref/jsref_obj_date.asp
var monthIndex = date.getMonth();
var dayIndex = date.getDay();
var monthArray = ['January',....];
var dayArray = ['Sunday',...]
console.log(monthArray[monthIndex] + "-" + dayArray[dayIndex]);

Parsing date string and retrieving day with Javascript

I've had a look through some of the suggestions in similar answers here but I can't find much that helps me.
Say I have a string that contains a date and a number: 2014-06-24 00:00:00
How would I parse it in a way that I can return this: 2014-06-24 00:00:00 Tuesday
Using date.parse as such:
new Date(Date.parse('2014-06-24 00:00:00'))
gives me the following result:
Tue Jun 24 2014 00:00:00 GMT+0100 (GMT Daylight Time)
Use methods getDay(),getDate() etc. to extract fields and format resulting string.
There are several JS sprintf implementations:
https://stackoverflow.com/a/3932473/2053898
https://github.com/alexei/sprintf.js
html
<div id="demo"></div>
js
//var a = new Date();
var a = new Date(Date.parse('2014-06-24 00:00:00'))
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
year = a.getFullYear()
month = a.getMonth()
date = a.getDate()
hour = a.getHours()
minutes = a.getMinutes()
seconds = a.getSeconds()
day = a.getDay()
alert(year + "-" + month+ "-" + date + " " + hour + ":" + minutes + ":" + seconds + " " + days[a.getDay()])
document.getElementById("demo").innerHTML = year + "-" + month+ "-" + date + " " + hour + ":" + minutes + ":" + seconds + " " + days[a.getDay()]
you can check the demo here
http://jsfiddle.net/victor_007/7ohh7mjv/
http://momentjs.com is a great, powerful library for easy date manipulation. Worth using if you're doing a lot of it. To get 2014-06-24 00:00:00 Tuesday you could do (after linking in the library, of course).
var m = moment("2014-06-24T00:00:00");
var output = m.format('YYYY-MM-DD hh:mm:ss dddd');
But, really, check out the docs, because this is just the tip of the iceberg: http://momentjs.com/docs/#/parsing/string-format/

Validating date in javascript with format d, MMM yyyy

How can i validate a date input by the user to make sure that the date entered is within the accepted limit
(e.g. date does not exceed 29 for feb, 30 for apr, jun, and nov and 31 for jan, mar, may, jul, aug, oct and dec) and the months not exceeding 12?
I have tried to add in conditions and the && simply does not work for me as it always returns an error.
My javascript function is as below:
function parseDate(s)
{
var dP = s.split("/");
var date = new Date(dP[2], (dP[1] - 1), dP[0]);
var dateStrParts = date.toString().split(" ");
return (date.getDate() + ", " + dateStrParts[1] + " " + dateStrParts[3]);
}
I have an onchange currently that will convert the month number to month name from user input and i believe i need to add another function for validation.
Hence how could i write the validation function and how should i add it into my onchange event?
There is no submit button for the date.
Thanks!
Use isNaN to check Date.parse()
function parseMyDate(s){
if (isNaN(Date.parse(s))){
alert("Your input has no logic at all");
return;
}
var dateParts = s.split("/");
var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
var dateStrParts = date.toString().split(" ");
return (date.getDate() + ", " + dateStrParts[1] + " " + dateStrParts[3]);
}
console.log(parseMyDate("31/02/2014"));
EDIT JSFiddle Demo

Javascript Date Object Issues With First Day of Month

I'm working with Javascript dates, and I'm getting a bit confused with trying to take a date from a string.
This is the code I have:
var formatDate = function(dateObj) {
// make sure date values are two digits and months start at 1
var adjMonth = dateObj.getMonth() + 1;
var adjDate = dateObj.getDate();
if (adjMonth < 10) adjMonth = '0' + adjMonth;
if (adjDate < 10) adjDate = '0' + adjDate;
// build and return dateStr
var dateStr = dateObj.getFullYear() + '-' + adjMonth + '-' + adjDate;
return dateStr;
};
$(document).ready(function() {
var testIn1 = "2012-02-01";
var testDate1 = new Date(testIn1);
var testDate1Str = formatDate(testDate1);
var testIn2 = "2012-01-31";
var testDate2 = new Date(testIn2);
var testDate2Str = formatDate(testDate2);
$('#output').html("---Input = '" + testIn1 + "':<br>" + testDate1 + "<br>" + testDate1Str + "<br>"
+"---Input = '" + testIn2 + "':<br>" + testDate2 + "<br>" + testDate2Str + "<br>");
});​
Results I get from this are:
---Input = '2012-02-01':
Tue Jan 31 2012 18:00:00 GMT-0600 (CST)
2012-01-31
---Input = '2012-01-31':
Mon Jan 30 2012 18:00:00 GMT-0600 (CST)
2012-01-30
Which makes no sense to me, why are the days one off? Doesn't seem sensical to get 2012-01-31 from 2012-02-01... What am I missing here?
It looks like Date.parse uses 00:00:00 GMT if you don't pass a time, and it will be 18:00:00 the previous day in your time zone (GMT-6). If you do pass an explicit time, then this behaviour is suppressed:
Date.parse(testIn1 + " 00:00:00");

Javascript Date

I am trying to get a month range to insert into a CAML query, ie: 2010-09-01 and 2010-09-30.
I have used the following code to generate these two values:
var month = "10/2010";
var monthArray = month.split("/");
var startDate = new Date(monthArray[1], monthArray[0]-1, 1);
var endDate = new Date(startDate);
endDate.setMonth(startDate.getMonth()+1, startDate.getDate()-1);
Running this code:
alert("month: " + month +
"\nstartDate: " + startDate.toDateString() +
"\nendDate: " + endDate.toDateString());
generates the correct dates (corporate policy requires IE7):
---------------------------
Windows Internet Explorer
---------------------------
month: 10/2010
startDate: Fri Oct 1 2010
endDate: Sun Oct 31 2010
---------------------------
OK
---------------------------
However, when I attempt to parse into ISO 8601 format (for the CAML query), I get the wrong dates.
var endISO8601 = endDate.getUTCFullYear() + "-" +
endDate.getUTCMonth() + "-" +
endDate.getUTCDate() + "T19:59:00Z";
alert("endDate: " + endDate.toDateString() +
"\nendISO8601: " + endISO8601);
---------------------------
Windows Internet Explorer
---------------------------
endDate: Sun Oct 31 2010
endISO8601: 2010-9-31T19:59:00Z
---------------------------
OK
---------------------------
I am not allowed to use Datejs, unfortunately.
I think you are just forgetting to add one to the month (january is 0 in javascript)

Categories