Need clarity on javascript date logic - javascript

I am getting false for both conditions
localStorage.getitem("dl-visited-date") // "Mon Oct 07 2013 13:58:18 GMT-0400 (EDT)";
currentDate // Tue Oct 08 2013 14:18:26 GMT-0400 (EDT)
currentDate > localStorage.getItem("dl-visited-date") //false
currentDate < localStorage.getItem("dl-visited-date") //false

localStorage.getitem does return a string (your Date object was implicitly stringified when you stored it in the localstorage). If you compare this with a Date object, both will be casted to numbers, but while this works for the Date object the string will become NaN. And that compares false to anything.
You will need to parse it before (using the Date constructor):
var date = new Date(localStorage.getitem("dl-visited-date")),
currentDate = new Date();
If you want to test them for equality, you will need to use plain numbers instead. Use Date.parse then:
var dateStamp = Date.parse(localStorage.getitem("dl-visited-date")),
currentDateStamp = Date.now();

$(function () {
var dateformate = localStorage.getItem("selectedFormat");
alert(dateformate);
});

Related

What if I give parameter for Date.prototype.getTime()?

I create date in two ways:
new Date('some date').getTime();
new Date().getTime('some date');
I did it before I had read on MDN, that Date.prototype.getTime() doesn't have parameter. It means second way is wrong. Nevertheless, it gives the same date value the right way gives (new Date('*some date*').getTime();) but amount of milliseconds is different and I don't get why.
Could someone explain me?
(function () {
let dateToCount = "Jan 01, 2022 00:00:00";
let date1 = new Date(dateToCount).getTime();
let date2 = new Date().getTime(dateToCount);
console.log(Date(date1).toString()); // Tue Oct 19 2021 22:41:59 GMT+0300 (Eastern European Summer Time)
console.log(Date(date2).toString()); // Tue Oct 19 2021 22:41:59 GMT+0300 (Eastern European Summer Time)
console.log(`date1 = ${date1} ms`); // date1 = 1640988000000 ms
console.log(`date2 = ${date2} ms`); // date2 = 1634672519002 ms
console.log(`date1 - date2 = ${+date1 - (+date2)} ms`); // date1 - date2 = 6315480998 ms
})();
it gives the same date value the right way gives
No, it doesn't - it just that when you were debugging with console.log(Date(date1).toString()); you fell in yet another trap: missing the new operator in the call the Date. As MDN puts it:
Calling the Date() function (without the new keyword) returns a string representation of the current date and time, exactly as new Date().toString() does. Any arguments given in a Date() function call (without the new keyword) are ignored; regardless of whether it’s called with an invalid date string — or even called with any arbitrary object or other primitive as an argument — it always returns a string representation of the current date and time.
So if you fix that as well, you'll realise that the two different millisecond values you get back from getTime() actually do represent two different dates:
const dateToCount = "Jan 01, 2022 00:00:00";
const date1 = new Date(dateToCount).getTime();
const date2 = new Date().getTime(dateToCount);
console.log(new Date(date1).toString()); // Sat Jan 01 2022 00:00:00, as expected
console.log(new Date(date2).toString()); // Surprise!
console.log(`date1 = ${date1} ms`);
console.log(`date2 = ${date2} ms`);

How to format "Fri Sep 11 2020 02:00:00 GMT-0400 (EDT)" to simply mm.dd.yy using Google App Script>

I am trying to convert my date column from a google sheet from "Fri Sep 11 2020 02:00:00 GMT-0400 (EDT)" to simply 09.11.20. I tried this code but it does not convert and throws an error. Please advise:
var date1 = sheet.getRange('P2:P2').getValues(); //my date field
var date_formatted = Utilities.formatDate(date1, "GMT", "MM.dd.yy");
What do I need to change here?
Try var date1 = sheet.getRange('P2').getValue()
getValues() returns a multidimensional array.
Since you want to get only cell P2 you should use
sheet.getRange('P2').getValue() instead.
assuming the latter returns a date object, this would probably work:
var date1 = sheet.getRange('P2').getValue(); //my date field
var date_formatted = Utilities.formatDate(date1, "GMT", "MM.dd.yyyy");
If the result you are getting is the day of yesterday, then try this:
var date1 = sheet.getRange('P2').getValue(); //my date field
var df = Utilities.formatDate(date1, "GMT", "MM.dd.yyyy").split('.');
var date_formatted = `${df[0]}.${parseInt(df[1])+1}.${df[2]}`;

Date objects in dictionaries change timezone in Javascript/Node

To avoid day light saving issues with date objects, I use UTC. For example:
new Date(2019,8,20, 9, 0) gives 2019-09-20T08:00:00.000Z
new Date(Date.UTC(2019,8,20, 9, 0)) gives 2019-09-20T09:00:00.000Z -- what I want
My issue now is that when I add that date to a dictionary, It uses local timezone somehow. For example:
const b = {}
b[Date(Date.UTC(2019,8,20, 9, 0))] = true
gives the following:
{ 'Fri Sep 20 2019 10:00:00 GMT+0100 (IST)': true }
you can do the following to get the UTC time -
var utcDate = new Date(Date.UTC(2019,8,20,9,0)).toUTCString()
b[utcDate] = true
EDIT
You should use ISOString() format to get format like 2019-09-20T09:00:00.000Z
var utcDate = new Date(Date.UTC(2019,8,20,9,0)).toISOString()
b[utcDate] = true

Remove time from GMT time format

I am getting a date that comes in GMT format, Fri, 18 Oct 2013 11:38:23 GMT. The problem is that the time is messing up the timeline that I am using.
How can I strip out everything except for the actual date?
If you want to keep using Date and not String you could do this:
var d=new Date(); //your date object
console.log(new Date(d.setHours(0,0,0,0)));
-PS, you don't need a new Date object, it's just an example in case you want to log it to the console.
http://www.w3schools.com/jsref/jsref_sethours.asp
Like this:
var dateString = 'Mon Jan 12 00:00:00 GMT 2015';
dateString = new Date(dateString).toUTCString();
dateString = dateString.split(' ').slice(0, 4).join(' ');
console.log(dateString);
I'm using this workaround :
// d being your current date with wrong times
new Date(d.getFullYear(), d.getMonth(), d.getDate())
You could use Moment.js, a library that provides many helper functions to validate, manipulate, display and format dates and times in JavaScript.
Using Moment.js lib:
var dateString = new Date('Mon Jan 12 00:00:00 GMT 2015');
moment(dateString).format('YYYY-MM-DD HH:mm');
Or simplified:
moment('Mon Jan 12 00:00:00 GMT 2015').format('YYYY-MM-DD HH:mm')
Well,
Here is my Solution
let dateString = 'Mon May 25 01:07:00 GMT 2020';
let dateObj = new Date(dateString);
console.log(dateObj.toDateString());
// outputs Mon May 25 2020
See its documentation on MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString
Just cut it with substring:
var str = 'Fri, 18 Oct 2013 11:38:23 GMT';
str = str.substring(0,tomorrow.toLocaleString().indexOf(':')-3);
In this case you can just manipulate your string without the use of a Date object.
var dateTime = 'Fri, 18 Oct 2013 11:38:23 GMT',
date = dateTime.split(' ', 4).join(' ');
document.body.appendChild(document.createTextNode(date));
You can first convert the date to String:
String dateString = String.valueOf(date);
Then apply substring to the String:
dateString.substring(4, 11) + dateString.substring(30);
You need to take care as converting date to String will actually change the date format as well.

Date Comparison always returns false no matter which operator used

I'm pulling my hair out a little here. I understand that an == comparison will always return false between two date objects. But really can't understand why this code returns false every time regardless which way round I set the operator.
var prevWeek = response.prevWeek // The date to compare.
, pickedDate = prevWeek.split("-");
var pickedDate = new Date(pickedDate[0], pickedDate[1], pickedDate[2]);
var todaysDate = new Date();
console.log(pickedDate); // logs Thu Apr 17 2014 00:00:00 GMT+0100 (GMT)
console.log(todaysDate); // logs Fri Nov 15 2013 18:30:13 GMT+0000 (GMT)
var compareValueOf = pickedDate.valueOf() < todaysDate.valueOf();
console.log(compare); // always returns false
var compare2 = pickedDate < todaysDate;
console.log(compare2); // always returns false
var compare3 = pickedDate.getTime() < todaysDate.getTime();
console.log(compare3); // always returns false
that's because the picedDate IS smaller than the todaysDate (2014 > 2013, not the other way around) ;)
if pickedDate is set in 2014, and todaysDate in 2013, there is no way pickedDate can be smaller than todaysDate.
I see a couple of problems with your code.
var prevWeek = response.prevWeek // The date to compare.
, pickedDate = prevWeek.split("-");
I assume respone.prevWeek is a human readable string, like '2013-03-17' for the 17:th of march 2013. When you create a new date object you get the 17:th of april 2013 because the Date-object expects to get the month in 0-11 instead of 1-12. (The year is ok, and so is the day)
var pickedDate = new Date(pickedDate[0], pickedDate[1], pickedDate[2]);
var todaysDate = new Date();
console.log(pickedDate); // logs Thu Apr 17 2014 00:00:00 GMT+0100 (GMT)
console.log(todaysDate); // logs Fri Nov 15 2013 18:30:13 GMT+0000 (GMT)
Notice that you now have a time in pickedDate as 2014-04-18 00:00:00.000 (including microseconds) and in todaysDate 2013-11-15 18:30:13.324 (including microseconds, the exact value is not know so I made it up)
var compareValueOf = pickedDate.valueOf() < todaysDate.valueOf();
console.log(compare); // always returns false
Above you assign the value into compareValueOf but logs the value of compare. But even if you did log the right variable you should get false since a date in 2014 isn't less than a date in 2013.
var compare2 = pickedDate < todaysDate;
console.log(compare2); // always returns false
Another way to compare date objects, that is ok to use. But once again you get false since you are asking if a date in 2014 is less than a date in 2013. It isn't.
var compare3 = pickedDate.getTime() < todaysDate.getTime();
console.log(compare3); // always returns false
Another compare that is exactly like the one above where you use .valueOf() since getTime() gives the exact same value (number of milliseconds since 1 January 1970 00:00:00 UTC). And once again you get false since the picked date is in the future.
If you only want to compare the date-part you could make sure that the time-part of todaysDate is zero by running todaysDate.setHours(0,0,0,0);. Notice that there are 4 parameters: hours, minutes, seconds and microseconds.

Categories