javascript add 1ms to a string date - javascript

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)

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)

Stop date to epoch conversion in 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/

Return documents created since midnight

I want to find all document's created since midnight, regardless of the users timezone. If the users on Pacific time, it should show all their documents since midnight Pacific. Same with Eastern time.
I'm on Eastern time and this works for me:
var d = new Date();
var midnight = d.setHours(0,0,0,0); // last midnight
var count = Items.find({
username: Meteor.user().username,
createdAt: { $gt: midnight }
}).count();
But my client is on CST and it doesn't work for him. It instead shows documents created since like 10pm or 11pm CST the previous day. So this seems like a timezone issue for me.
Assuming that this is a client-side issue only (all of the times are stored in UTC on the server) then you can get the UTC adjusted time for midnight of the users current timezone by doing the following:
var now = new Date();
var midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var midnight_utc = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
See this fiddle: https://jsfiddle.net/Lbk1vo0j/1/
For example, for my current time zone (eastern) I get the following values for now, midnight, and midnight_utc (when printing the Date objects using the toLocaleString() method):
3/30/2015, 3:06:39 PM
3/30/2015, 12:00:00 AM
3/29/2015, 8:00:00 PM
try setUTCHours(0, 0, 0, 0);. It gets the Coordinated Universal Time that should be the same for every user.
I had similar requirement so I did used following method,
Created function to map datetime to _id
used that id to get my data.
Function that I am using is
function objectIdWithTimestamp(timestamp){
// Convert string date to Date object (otherwise assume timestamp is a date)
if (typeof(timestamp) == 'string') { timestamp = new Date(timestamp); }
// Convert date object to hex seconds since Unix epoch
var hexSeconds = Math.floor(timestamp/1000).toString(16);
// Create an ObjectId with that hex timestamp
var constructedObjectId = ObjectId(hexSeconds + "0000000000000000");
return constructedObjectId
}
using it
db.collection.find({_id:{$gte:objectIdWithTimestamp(Y/m/d H:i:s)}})
I will advice you try moment library and resolve the time zone problem. Where ever client code is getting executed, get its last midnight time, convert it to UTC time & then easily retrieve the information from MongoDb. Few moment library usage example, for more detail refer here
var str = "2013-12-01"
moment.tz(str, "America/Los_Angeles").format(); // 2013-06-01T00:00:00-07:00
moment.tz(str, "America/New_York").format(); // 2013-06-01T00:00:00-04:00
Minutes since midnight
You can get the minutes since midnight from the user's perspective. Try using it to query the server for changes since x minutes ago.
var d = new Date();
console.log(d);
var now = d.getTime();
d.setHours(0,0,0,0);
var midnight = d.getTime();
var minutes_ago = Math.floor((now-midnight) / (60 * 1000));
console.log(minutes_ago);
output:
Date {Thu Apr 02 2015 16:12:54 GMT-0700 (PDT)}
972
This should work:
var d = new Date();
var midnight = d.setUTCHours(0,0,0,0); // last midnight everywhere
var count = Items.find({
username: Meteor.user().username,
createdAt: { $gt: midnight }
}).count();

Save date 'without' time in JavaScript

At the moment I save my date like this: ISODate("2014-11-17T16:19:16.224Z"), but I want this result: ISODate("2014-11-16T23:00:00Z"). How can I do this?
An easier alternative is to use Date.setHours() - in single call you can set what you need - from hours to milliseconds. If you just want to get rid of the time.
var date = new Date();
date.setHours(0,0,0,0);
console.log ( date );
Set the parts you don't want saved to 0. In your example, you would set the minutes, seconds, and milliseconds to 0.
var date = new Date();
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
var isoDateString = date.toISOString();
console.log(isoDateString);
Or, a less verbose option:
var date = new Date();
var isoDateString = date.toISOString().substring(0,10);
console.log(isoDateString);
To Save a date without a time stamp:
let date = new Date().toLocaleDateString('en-US');
console.log(date)
// OUTPUT -> m/d/yyyy
Use this to find options to add as paramaters for the toLocaleDateString function

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