How can I convert a date into an integer? - javascript

I have an array of dates and have been using the map function to iterate through it, but I can't figure out the JavaScript code for converting them into integers.
This is the array of dates:
var dates_as_int = [
"2016-07-19T20:23:01.804Z",
"2016-07-20T15:43:54.776Z",
"2016-07-22T14:53:38.634Z",
"2016-07-25T14:39:34.527Z"
];

var dates = dates_as_int.map(function(dateStr) {
return new Date(dateStr).getTime();
});
=>
[1468959781804, 1469029434776, 1469199218634, 1469457574527]
Update:
ES6 version:
const dates = dates_as_int.map(date => new Date(date).getTime())
The getTime() method on the Date returns an “ECMAScript epoch”, which is the same as the UNIX epoch but in milliseconds. This is important to note as some other languages use UNIX timestamps which are in in seconds.
The UNIX timestamp and is equivalent to the number of milliseconds since January 1st 1970. This is a date you might have seen before in databases or some apps, and it’s usually the sign of a bug.

Using the builtin Date.parse function which accepts input in ISO8601 format and directly returns the desired integer return value:
var dates_as_int = dates.map(Date.parse);

Here what you can try:
var d = Date.parse("2016-07-19T20:23:01.804Z");
alert(d); //this is in milliseconds

You can run it through Number()
var myInt = Number(new Date(dates_as_int[0]));
If the parameter is a Date object, the Number() function returns the number of milliseconds since midnight January 1, 1970 UTC.
Use of Number()

if your format date is YYYY/M/D you can use this code :
let yourDate = momentjs(new Date().toLocaleDateString(), 'M/D/YYYY').format('YYYY-MM-DD');
let newDate = Number(yourDate.slice(0, 10).split('-').join(''));

Related

How to convert the DD-MM-YYYY HH:mm format to epoch time using moment or js?

I have a date time picker and it omits date in format of a DD-MM-YYYY HH:mm a format. I want to convert it into epoch time to store it in the database backend.
I have tried using the following methods so far, but all of them return NaN as output:
var loadingPlannedUnTime = this.state.loadingPlannedUnTime;
console.log("normal conversion"+loadingPlannedUnTime);
//returns 9-08-2020 15:08:00
//Moment method
var loadingPlannedUnTime = moment(this.state.loadingPlannedUnTime).unix();
console.log("moemnt"+loadingPlannedUnTime)
//Returns NaN
//JS getTime() method
var pickupDateTime = new Date(this.state.loadingPickupTime);
var loadingPickupTime = pickupDateTime.getTime();
console.log("new date and gettime"+loadingPickupTime)
//Returns NaN
What is the correct method to convert it to epoch time?
https://momentjs.com/docs/
If you know the format of an input string, you can use that to parse a moment.
moment("12-25-1995", "MM-DD-YYYY");
const x = moment('24-12-2019 09:15', "DD-MM-YYYY hh:mm");
console.log(x.format())
<script src="https://rawgit.com/moment/moment/2.2.1/min/moment.min.js"></script>
const matches = loadingPlannedUnTime.match(/(\d{1,2})-(\d{1,2})-(\d{2,4}) (\d{1,2}):(\d{1,2}):(\d{1,2})/);
if (!!matches) {
// new Date(year, month, day, hours, minutes, seconds, milliseconds)
const epoch = new Date(matches[3], matches[2] - 1, matches[1], matches[4], matches[5], matches[6]).getTime();
console.log(epoch);
}

convert string to UTC time using jquery

I am trying to convert string to time, the string i have are in this format, '8:3' and '16:45'.
I want to convert UTC time in jQuery.
You can write your function to create UTC date with the time string.
function toUTC(str) {
let [h, m] = str.split(':');
let date = new Date();
date.setHours(h, m, 0)
return date.toUTCString();
}
console.log(toUTC('8:3'))
console.log(toUTC('16:45'))
You don't need jQuery for such operations. Just the simple Date object will do the trick. Say you want to convert time from a specific date.
let date = new Date('2020-04-01'); // leave the Date parameter blank if today
date.setHours(16); // must be 24 hours format
date.setMinutes(45);
let theUTCFormat = date.getUTCDate();
Cheers,

Compare two dates using valueOf()

const startDayOfTheWeek: number = moment().startOf('isoweek' as moment.unitOfTime.StartOf).valueOf();
if (this.card.dateScheduled.valueOf() < startDayOfTheWeek) {
this.card.dateScheduled = this.card.dateDue;
}
When using valueOf(), this.card.dateScheduled.valueOf() this gives me a value of the actual date. Not the millisecond relative to 1970 (a.k.a the Unix timestamp/epoch).
Why is that?
In moment.js there are many useful methods for comparing dates like isAfter, isBefore. So in your case use:
if (moment(this.card.dateScheduled).isBefore(startDayOfTheWeek))
I think you can take the benefits of inbuilt functionality.
Here is an example to compare dates in javascript.
const first = +new Date(); // current date
const last = +new Date(2014, 10, 10); // old date
console.log(first);
console.log(last);
// comparing the dates
console.log(first > last);
console.log(first < last);

How to get a string of max date from an array of string dates?

What would be the most elegant way to get max date from an array of strings like below?
var dates = ["2018-12-29T15:23:20.486695Z", "2018-12-29T15:23:21.613216Z", "2018-12-29T15:23:22.695710Z", "2018-12-29T15:23:24.013567Z", "2018-12-29T15:23:25.097649Z", "2018-12-29T15:23:26.692125Z", "2018-12-29T15:23:27.918561Z", "2018-12-29T15:23:29.217879Z", "2018-12-29T15:23:30.468284Z", "2018-12-29T15:23:31.548761Z"]
I have tried:
var timestamps = dates.map(date => Date.parse(date));
var max_date = Math.max.apply(Math, timestamps)
But this leaves me with a timestamp that I would need to convert back to the exact original format (and I don't know how to do that).
​
You could compare the ISO 8601 date like strings and take the greater value.
var dates = ["2018-12-29T15:23:20.486695Z", "2018-12-29T15:23:21.613216Z", "2018-12-29T15:23:22.695710Z", "2018-12-29T15:23:24.013567Z", "2018-12-29T15:23:25.097649Z", "2018-12-29T15:23:26.692125Z", "2018-12-29T15:23:27.918561Z", "2018-12-29T15:23:29.217879Z", "2018-12-29T15:23:30.468284Z", "2018-12-29T15:23:31.548761Z"],
latest = dates.reduce((a, b) => a > b ? a : b);
console.log(latest);
That's the format provided by toISOString on Date. So you take your timestamp value, feed it into new Date, and use toISOString on the result:
console.log(new Date(max_date).toISOString());
Example:
var dates = [
"2018-12-29T15:23:20.486695Z",
"2018-12-29T15:23:21.613216Z",
"2018-12-29T15:23:22.695710Z",
"2018-12-29T15:23:24.013567Z",
"2018-12-29T15:23:25.097649Z",
"2018-12-29T15:23:26.692125Z",
"2018-12-29T15:23:27.918561Z",
"2018-12-29T15:23:29.217879Z",
"2018-12-29T15:23:30.468284Z",
"2018-12-29T15:23:31.548761Z"
];
var timestamps = dates.map(date => Date.parse(date));
var max_date = Math.max.apply(Math, timestamps)
console.log(new Date(max_date).toISOString());
Note that you get "2018-12-29T15:23:31.548Z" rather than "2018-12-29T15:23:31.548761Z" because you've parsed the strings to JavaScript dates, and JavaScript dates only hold milliseconds, not microseconds.

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