I have to save a date to localStorage and when the page is refreshed I want to calculate how much time has passed since then.
Now, here's the problem: localStorage saves the date as a string so after it is saved in localStorage trying to calculate the difference between those two dates returns NaN.
Try this in your javascript console:
var a = new Date();
var b = new Date();
console.log(b - a); //this works
localStorage.a = a;
localStorage.b = b;
console.log(localStorage.b - localStorage.a); //this doesn't work
I also tried JSON.stringify and JSON.parse trying to keep the date object intact, but that doesn't work either.
My guess is that I have to parse the date in the localStorage. If there is not a better method, how can I do that?
Demo: http://jsfiddle.net/AuhtS/
Code:
var a = new Date();
var b = new Date();
console.log(b - a); //this works
localStorage.a = a;
localStorage.b = b;
a = Date.parse(localStorage.a); // parse to date object
b = Date.parse(localStorage.b);
console.log(b - a); // now, this will work
Reason
Everything is stored as a string in localStorage.
So when you do localStorage.b - localStorage.a, what you're attempting is trying to subtract one string from another. Which is why it doesn't work.
To store a date in localStorage, simply do
localStorage['key'] = ''+myDate.getTime();
And to restore it :
var myDate = new Date(parseInt(localStorage['key'], 10));
(you might also want to test it's defined before)
It also works with duration (a date minus another one) : Simply use the value as long (millisecondes) and convert to and from a string.
Note that JSON doesn't include a standardized date format. Don't use JSON for dates.
I'd use this:
var d1 = new Date();
localStorage.setItem("key", d1.getTime());
var d2 = new Date(parseInt(localStorage.getItem[key]));
all that is missing is proper null validation.
You can simply go for:
var date1 = <date1>
var date2 = <date2>
localStorage.setItem('date1', date1.toString())
localStorage.setItem('date2', date2.toString())
var date1 = new Date(localStorage.getItem('date1'))
var date2 = new Date(localStorage.getItem('date2'))
var diff = date1 - date2
In my case, I need it in Date type. Therefore, here it is:
var a = new Date();
localStorage.a = a;
var c = new Date(localStorage.a);
localStorage.setItem("date", new Date().toString());
you can directly add like this
I believe that localStorage only takes timestamps. Correct me if I am wrong. I suggest you use the moment library instead of the JS built in Date library.
moment is way easier to use and has some handy builtin functions.
One is toString() which allows you to parse the data as a string.
an example is:
// create a moment (the current time)
const now = moment()
// convert it to a timestamp to store it in localStorage
now.valueOf()
// get the data back in string format
now.toString()
Moment also has the useful .fromNow() method, which allow you to get the time difference from the date was created to the moment it was edited.
I hope this help. read the docs for moment for more info here: https://momentjs.com/docs/
Related
Assigning a Date variable to another one will copy the reference to the same instance. This means that changing one will change the other.
How can I actually clone or copy a Date instance?
Use the Date object's getTime() method, which returns the number of milliseconds since 1 January 1970 00:00:00 UTC (epoch time):
var date = new Date();
var copiedDate = new Date(date.getTime());
In Safari 4, you can also write:
var date = new Date();
var copiedDate = new Date(date);
...but I'm not sure whether this works in other browsers. (It seems to work in IE8).
This is the cleanest approach
let date = new Date()
let copyOfDate = new Date(date.valueOf())
console.log(date);
console.log(copyOfDate);
Update for 2021
In one respect the notion of cloning a Date object sounds grander than it really is. As far as I can tell, there’s only one piece of instance data, and that is the stored time. What we’re really doing is making a new object with the same time.
Whatever may have been the case in the past, the new Date() constructor definitely accepts a Date object as a single argument:
const date = new Date(); // With or without an argument.
const date2 = new Date(date); // Clone original date.
The Specification at https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date at step 4(b) indicates that a Date object is definitely acceptable, and that this is equivalent to new Date(date.valueOf()), as suggested by some of the answers above. As I said, all you’re really doing is making a new Date object with the same time as the other.
You’ll also find that the documentation at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date has been updated to include this.
var orig = new Date();
var copy = new Date(+orig);
console.log(orig, copy);
Simplified version:
Date.prototype.clone = function () {
return new Date(this.getTime());
}
I found out that this simple assignmnent also works:
dateOriginal = new Date();
cloneDate = new Date(dateOriginal);
But I don't know how "safe" it is. Successfully tested in IE7 and Chrome 19.
function cloneMyDate(oldDate){
var newDate = new Date(this.oldDate);
}
I was passing oldDate to function and generating newDate from this.oldDate, but it was changing this.oldDate also.So i used the above solution and it worked.
For chrome it works:
//Thu Nov 03 2022 11:43:00
**const date = new Date(2022,10,03,11,43,0);
const date2 = new Date(date);**
now changing date2 will have no impact on the date
var innerDate = document.getElementById('datetimepicker3').value;
The format I get from this line is: innerDate: "2021/07/07 14:00"
But I need to parse the date and time information here. How can I convert Start Date and Start Time into two separate variables?
I would recommend to parse that string with moments.js and then depending on your needs either get the individual parts for calculations or apply needed formatting
Example available at https://jsfiddle.net/Ly6qen3w/
let innerDateInput = "2021/07/07 14:00";
let innerDateMoment = moment(innerDateInput, "YYYY/MM/DD hh:mm");
console.log("Date:"+innerDateMoment.format("YYYY-MM-DD"));
console.log("Time:"+innerDateMoment.format("hh:mm"));
Try this:
var innerDate = new Date(document.getElementById('datetimepicker3').value)
Or you can attach an event handler to get the date whenever it changes
<script type="text/javascript">
$("#datetimepicker3").on("dp.change", function (e) {
let date = e.date;
console.log(date);
// no need to convert to a date
});
</script>
You can simple get that in different variable using various methods that are provided by JavaScript to get everything.
You can do is(id it's a date object else you have to convert it to date object)
let startDate = new Date(innerDate).getDate() + "/" + new Date(innerDate).getMonth() + "/" + new Date(innerDate).getFullYear();
let startTime = new Date("2021/07/07 14:00").getHours() +":"+ new Date("2021/07/07 14:00").getMinutes()
If you want something else you can retrieve that too with methods such as milliseconds,UFC time etc.
If you find this messy I would suggest you to use moment.js.
https://momentjs.com/
I'm trying to get the current date - 3 months and use it in a postman Pre-request script. I'm told it uses javascript, but it doesn't seem to be working.
The error I get is:
There was an error in evaluating the Pre-request Script: TypeError:
startDate.setMonth is not a function
Here is what I have:
// setup start date
var startDate = Date();
startDate.setMonth(startDate.getMonth() - 3);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Syntax
JavaScript Date objects can only be instantiated by calling JavaScript Date as a constructor: calling it as a regular function (i.e. without the new operator) will return a string rather than a Date object; unlike other JavaScript object types, JavaScript Date objects have no literal syntax.
so
Date();
needs to be
new Date();
Try change var startDate = Date(); to var startDate = new Date();
As an alternative, Postman comes with the moment module built in so you could do something like this:
var moment = require("moment")
var startTime = moment().subtract(3, 'months')
Or you could obviously use native JavaScript, worth knowing a couple of different ways though.
I'm trying to use the Calendar API to pull up some events based on datepicker output. The issue that i'm facing with my AppScript is formatting properly the value that i get from the datepicker that will serve as input for the getEventsForDay() function.
function testing(){
var z = CalendarApp.getCalendarsByName("X")[0];
var date = new Date('2016-10-12');
var dateformatted =Utilities.formatDate(date), "GMT", "yyyy-MM-dd hh:mm:ss a");
var a = z.getEventsForDay(dateformatted, {search: 'OOO'});
The output of a into this scenario is a empty object - which is expected because this formatting is not working at all. (i've read 1000 posts that this should work).
For context as well, i have one working example with today's date, which it works fine becase the input is a new Date(). Here you go:
var datetoday = new Date();
var b = z.getEventsForDay(datetoday, {search: 'OOO'});
Any ideas on what i'm missing here?
Thanks in advance.
Since new Date() returns the Date object in UTC and not the local timezone, you may be querying the wrong day and hence the empty object if the other day does not have any events.
You can covert the date to the current timezone like
date.setTime(date.getTime() + date.getTimezoneOffset()*60*1000)
This should return the date in the local timezone and you will get the events for the correct day.
Hope it helps
Made some changes and now this works on the App Script:
var t = "2016-10-01";
var q = t.replace(/-/g,"/");
var a = new Date(q);
a.setTime(a.getTime() + a.getTimezoneOffset()*60*1000)
var w = z.getEventsForDay(a, {search: 'OOO'});
Logger.log(a);
Logger.log(w);
I have a form, where I need to do some validations by getting the current date and next date separately using javaScript.
I tried this code but it does not work correctly.
var currentDate = new Date();//get current date
var validdate=currentDate;
validdate.setDate(validdate.getDate()+1);
But what happens is when valid date changes to +1, then current date also changes to +1.
But I need it separately, means when I print the output: I get
currentDate = 5th May 2014;
validdate = 6th May 2014;
Then when again I print currentDate, it changes to "6th May 2014".
How to get the current date and next date without affecting each other?
instead of validdate = currentDate; try validdate = new Date();.
Your problem happens because in javascript when you pass an object to a value it is passed by reference and not by value. So when you change it you change even the original object because you don't actually have two different objects.
you are refering to same object instance for currentDate and validdate.
initialise them seperatly like below
currentDate = new Date();
validdate = new Date();
also rename your validdate to validDate for more readability.
to make a new copy of a Date object use following code
var validdate = new Date(currentDate.getTime());
now when you modify the validdate object it will not update currentDate
Try This
var currentDate = new Date();//get current date
alert(currentDate.toString());
var validdate=new Date();
validdate.setDate(currentDate.getDate()+1);
alert(validdate.toString());
alert(currentDate.toString());