Stop date to epoch conversion in javascript - javascript

I have a code where I try to set date 20 days back from current date on server. I have used a variable(say dateRange) in javascript to get current date. But on using the same variable second time for setDate() function value of dateRange is changed to epoch from date. I know I can convert epoch to date and proceed but is there a way to stop this automatic conversion.
var dateRange=new Date(currentDate);
dateRange = dateRange.setDate(dateRange.getDate() - 20);

setDate modifies the date object, and returns the epoch value. Just don't save the epoch value in dateRange, so you can use the date object after modifying it:
var currentDate = new Date();
var dateRange = new Date(+currentDate);
console.log(dateRange.toISOString());
dateRange.setDate(dateRange.getDate() - 20);
console.log(dateRange.toISOString());
Side note: Copying a date by doing var dateRange = new Date(currentDate); is/was unreliable on some browsers. In the above, I've changed it to var dateRange = new Date(+currentDate); (note the +, converting the date to its epoch value), which is reliable.

Internally dates are stored as milliseconds from the epoch date.
To achieve what you are trying to do you can subtract the number of milliseconds that corresponds to 20 days:
var currentDate = "2019-07-29T07:14:57.269Z";
var dateRange = new Date(currentDate);
var pastDate = new Date(dateRange - 1000 * 60 * 60 * 24 * 20);
console.log('current', currentDate);
console.log('20 days ago', pastDate);
anyway if you are doing a lot of date/time manipulations in your app i suggest you to use this library: https://momentjs.com/

Related

How to create All Day Calendar Event 14 days from now

I'm trying to create an all-day calendar event to 14 days from today using Google App Script but I keep getting the error
Exception: The parameters (String,String) don't match the method signature for CalendarApp.Calendar.createAllDayEvent.
My script is:
var SheetApp = SpreadsheetApp.getActiveSheet();
var SelectedRow = SheetApp.getActiveRange().getRowIndex();
var value = SheetApp.getRange(SelectedRow, 8).getValue(); //Name of the event
var eventCal = CalendarApp.getCalendarById("sampleemail#gmail.com");
eventCal.createAllDayEvent(value.toString(), new Date() + 14);
When you add a number to a Date object, the Date is automatically converted to its underlying value, i.e., the number of milliseconds since the epoch. The result of the addition will be that number of milliseconds plus 14, which is just a big integer. The createAllDayEvent() method expects a Date object rather than an integer.
To get a date that is 14 days from now, use Date.setDate(). This method has the benefit that it automatically takes care of rolling into the next month or next year as necessary, but be careful. The setDate() method modifies a Date object in place, but does not return the Date object. Instead, it returns the underlying value, i.e., the number of milliseconds since the epoch.
This means that you cannot just assign the result you get from setDate() to a variable in the hope of getting a valid Date. Something like const twoWeeksFromNow = new Date().setDate(new Date().getDate() + 14) will not work if you expect twoWeeksFromNow to contain a Date.
An easy way to get it right is to use a short utility function, like this:
function testCreateAllDayEvent() {
const twoWeeksFromNow = dateOffset_(new Date(), +14);
const eventCal = CalendarApp.getCalendarById("sample_email#gmail.com");
const sheet = SpreadsheetApp.getActiveSheet();
const eventTitle = sheet
.getRange('H' + sheet.getActiveRange().getRow())
.getDisplayValue();
eventCal.createAllDayEvent(eventTitle, twoWeeksFromNow);
}
/**
* Gets a new Date object that is offset by numDays from date.
*
* #param {Date} date The date from which to count.
* #param {Number} numDays The number of days to add or subtract from date.
* #return {Date} A new Date object that is offset by numDays from date.
*/
function dateOffset_(date, numDays) {
const newDate = new Date(date);
newDate.setDate(date.getDate() + numDays);
return newDate;
}
Change second parameter
new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 14)

javascript add 1ms to a string date

I have a var in js which is represented like so:
"lastTimeModified": "2019-02-26T11:38:20.222Z"
and I want to add to it 1ms
I have tried something like this:
dateObj = new Date();
dateObj.setMilliseconds(1);
var newDate = lastTimeModified + dateObj
but that doesn't seem to work.
If you can get your date in milliseconds than you can directly add 1 millisecond to it
var date = new Date(lastTimeModified) // convert string to date object
var mill = date.getMilliseconds() // Get millisecond value from date
mill += 1 // Add your one millisecond to it
date.setMilliseconds(mill) // convert millisecond to again date object
The below takes your time string turns it into a date object, gets the milliseconds since the 1. of January 1970 adds 1ms and turns it back into a date object
var newDate = new Date(new Date(lastTimeModified).getTime() + 1)

moment.js timezone get milliseconds

I'm trying to get number of days passed. I'm storing epoch (milliseconds) for date.
I'm reading startDate from database (date value of first record) in milliseconds and I want to find current epoch in specified timezone.
I tried this:
var startDate = rows[0]['MIN_DATE'];
var endDate = moment().tz("America/New_York");
Then to calculate difference, I used:
var oneDay = 24 * 60 * 60 * 1000;
var daysCount = Math.ceil((endDate - startDate) / (oneDay));
The value of startDate is:
1522821600000 which is: Wednesday, April 4, 2018 2:00:00 AM GMT-04:00 DST
The value of endDate is:
Moment_d: Wed Apr 04 2018 22:24:45 GMT-0400 (EDT)_isAMomentObject: true_isUTC: true_isValid: true_locale: Locale_offset: -240_pf: Object_z: Zone__proto__: Object
The value of daysCount is 2, how?
How can I get milliseconds instead of object from:
moment().tz("America/New_York");
To directly answer your question, use .valueOf() to get the value of moment.tz("America/New_York")
var endDate = moment.tz("America/New_York").valueOf()
I'm having difficulty understanding your question, but I believe you're trying to get the difference between the days considering the correct timezone. The following gives an accurate result using .diff() (https://momentjs.com/docs/#/displaying/difference/)
var timeZone = "America/New_York"
var startDate = 1522821600000
var momentStartDate = moment.tz(startDate,timeZone)
var momentEndDate = moment.tz(timeZone)
alert(momentEndDate.diff(momentStartDate, 'days') );
Use fromNow() function. It is very straight-forward.
Do like this :
moment(date).fromNow();
It will give you number of days passed if date is past as well as number of days to go if date is future.
Below are is example:
var date = 1522821600000; // your date
console.log(moment(date).fromNow());
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
Solved this with following statement:
var endDate = moment().tz("America/New_York").valueOf();

Getting incorrect dates converting timestamp with new Date

I'm trying to convert timestamp to Date but I'm getting incorrect dates. I'm working on a project with Angular and Typescript.
I have timestamps like:
1451642400 (1st january 2016) and 1454320800 (1st february 2016)
If I code:
date = new Date(1451642400);
console.log(date.toLocaleString());
date = new Date(1454320800);
console.log(date.toLocaleString());
I get:
17/1/1970 20:14:02 and 17/1/1970 20:58:40
when I should get:
1/1/2016 10:00:00 and 1/2/2016 10:00:00
What's the problem? How can I fix it?
You need to multiply your Unix Timestamp by 1000 so its in milliseconds..
If you do it like this, it will work:
date = new Date(1451642400 * 1000);
console.log(date.toLocaleString());
date = new Date(1454320800 * 1000);
console.log(date.toLocaleString());
The new Date()'s argument is in miliseconds. So try your timestamps with 1000 to make it in miliseconds.
var date = new Date(1451642400 * 1000);

convert iso date to milliseconds in javascript

Can I convert iso date to milliseconds?
for example I want to convert this iso
2012-02-10T13:19:11+0000
to milliseconds.
Because I want to compare current date from the created date. And created date is an iso date.
Try this
var date = new Date("11/21/1987 16:00:00"); // some mock date
var milliseconds = date.getTime();
// This will return you the number of milliseconds
// elapsed from January 1, 1970
// if your date is less than that date, the value will be negative
console.log(milliseconds);
EDIT
You've provided an ISO date. It is also accepted by the constructor of the Date object
var myDate = new Date("2012-02-10T13:19:11+0000");
var result = myDate.getTime();
console.log(result);
Edit
The best I've found is to get rid of the offset manually.
var myDate = new Date("2012-02-10T13:19:11+0000");
var offset = myDate.getTimezoneOffset() * 60 * 1000;
var withOffset = myDate.getTime();
var withoutOffset = withOffset - offset;
console.log(withOffset);
console.log(withoutOffset);
Seems working. As far as problems with converting ISO string into the Date object you may refer to the links provided.
EDIT
Fixed the bug with incorrect conversion to milliseconds according to Prasad19sara's comment.
A shorthand of the previous solutions is
var myDate = +new Date("2012-02-10T13:19:11+0000");
It does an on the fly type conversion and directly outputs date in millisecond format.
Another way is also using parse method of Date util which only outputs EPOCH time in milliseconds.
var myDate = Date.parse("2012-02-10T13:19:11+0000");
Another option as of 2017 is to use Date.parse(). MDN's documentation points out, however, that it is unreliable prior to ES5.
var date = new Date(); // today's date and time in ISO format
var myDate = Date.parse(date);
See the fiddle for more details.
Yes, you can do this in a single line
let ms = Date.parse('2019-05-15 07:11:10.673Z');
console.log(ms);//1557904270673
Another possible solution is to compare current date with January 1, 1970, you can get January 1, 1970 by new Date(0);
var date = new Date();
var myDate= date - new Date(0);
Another solution could be to use Number object parser like this:
let result = Number(new Date("2012-02-10T13:19:11+0000"));
let resultWithGetTime = (new Date("2012-02-10T13:19:11+0000")).getTime();
console.log(result);
console.log(resultWithGetTime);
This converts to milliseconds just like getTime() on Date object
var date = new Date()
console.log(" Date in MS last three digit = "+ date.getMilliseconds())
console.log(" MS = "+ Date.now())
Using this we can get date in milliseconds
var date = new Date(date_string);
var milliseconds = date.getTime();
This worked for me!
if wants to convert UTC date to milliseconds
syntax : Date.UTC(year, month, ?day, ?hours, ?min, ?sec, ?milisec);
e.g :
date_in_mili = Date.UTC(2020, 07, 03, 03, 40, 40, 40);
console.log('miliseconds', date_in_mili);
In case if anyone wants to grab only the Time from a ISO Date, following will be helpful. I was searching for that and I couldn't find a question for it. So in case some one sees will be helpful.
let isoDate = '2020-09-28T15:27:15+05:30';
let result = isoDate.match(/\d\d:\d\d/);
console.log(result[0]);
The output will be the only the time from isoDate which is,
15:27

Categories

Resources