how to convert a string to a Unix timestamp in javascript? - javascript

I want to convert a string "2013-09-05 15:34:00" into a Unix timestamp in javascript. Can any one tell how to do that? thanks.

You can initialise a Date object and call getTime() to get it in unix form. It comes out in milliseconds so you'll need to divide by 1000 to get it in seconds.
(new Date("2013/09/05 15:34:00").getTime()/1000)
It may have decimal bits so wrapping it in Math.round would clean that.
Math.round(new Date("2013/09/05 15:34:00").getTime()/1000)

try
(new Date("2013-09-05 15:34:00")).getTime() / 1000

DaMouse404 answer works, but instead of using dashes, you will use slashes:
You can initialise a Date object and call getTime() to get it in unix form. It comes out in milliseconds so you'll need to divide by 1000 to get it in seconds.
(new Date("2013/09/05 15:34:00").getTime()/1000)
It may have decimal bits so wrapping it in Math.round would clean that.
Math.round(new Date("2013/09/05 15:34:00").getTime()/1000)

For this you should check out the moment.s-library
Using that you could write something like:
newUnixTimeStamp = moment('2013-09-05 15:34:00', 'YYYY-MM-DD HH:mm:ss').unix();

I would go with date parse myself since it is the native solution. MDN documentation.
const datetimeString = '04 Dec 1995 00:12:00 GMT';
const unixTimestamp = Date.parse(datetimeString);
// unixTimestamp = 818035920000

Related

How can the Moment.js get the timestamp?

How can I get the timestamp after manipulating days in Moment.js?
I tried use:
var a = moment().subtract(10, 'days').calendar().getTime()
to get the timestamp, but failed.
It is not really clear what you mean by "timestamp".
To get the number of milliseconds since the Unix epoch, use moment().valueOf();. This corresponds to JS Date.getTime();.
To get the number of seconds since the Unix epoch, use moment().unix();.
To get the hour/minute/second as numbers, use moment().hour(); / moment().minute(); / moment().second();.
To get the ISO 8601 string (recommended for sending data over the wire), use moment().toISOString(); (e.g. "2013-02-04T22:44:30.652Z").
To print a user readable time, use moment().format();, e.g. moment().format('LTS') will return the localized time including seconds ("8:30:25 PM" for en-Us).
See moment.js - Display - Format for format specifiers.
Classic calendar formatting:
const daysBefore = moment().subtract(10, 'days').calendar();
for unix timestamp (current date minus 10 days):
const daysBefore = moment().subtract(10, 'days').unix();
Just remember, apply formatting after subtraction, as formatting returns a string, not momentjs object.
You can use moment().toDate() to get a Javascript Date object. Then you can get the timestamp with getTime().
calendar does not have method getTime(). You can format your time as follows:
let format = 'YYYYMMDD';
let a = moment().subtract(10, 'days').format(format);
console.log(a)
Try the following to get the timestamp:
moment().subtract(10, 'days')._d
try this one
moment().subtract(10, 'days').calendar().format('HH:MM:SS'); //get datetime
moment().subtract(1, 'days').calendar(); // Yesterday at 1:16 PM

Javascript 'yyyy-mm-dd hh:mm:ss' to timestamp

I want to convert datetime like '2015-05-01 05:13:43' into timestamp.
Is there Any way to do it using JavaScript?
With pure JS you can try with:
new Date(Date.parse('2015-05-01 05:13:43+0000')).getTime() / 1000
It's important to add +0000 at the end of the string - otherwise browser will use your local timezone and add/remove few hours from the result.
getTime method gives you time in ms - so we have to divide it by 1000.
You can do it!
let dateToConvert = '2015-05-01 05:13:43'
let date = new Date(dateToConvert)
let timestamp = date.getTime()

Comparing a datetime from a get request with the current date time in JavaScript

I need to get the difference (in minutes) from a datetime that I get froma get request in a string format to now.
According to my research, I can use moment.js to do so, but I haven't figured out now.
That format I am getting the date/time to be compared is as:
2017-02-10T20:52:13.885Z
I have already tried to do some operations with moment.js such as
moment().startof(comparedTime).fromNow())
But it returns nothing.
What are the alternatives and the best way to do this?
Can't you just use vanilla javaScript?
var getDate = '2017-02-10T20:52:13.885Z'; //get time from server
var parseDate = new Date(getDate).getTime(); //change string into Date object into milliseconds
var nowDate = Date.now(); //get current Date in milliseconds
var minutes = Math.round((nowDate-parseDate)/1000/60); //subtract times, count seconds (/1000), count minutes (/60)
console.log(minutes);
You need to create a moment object by passing the date string in. e.g.
myDate = moment(myISOString)
https://momentjs.com/docs/#/parsing/
Then you can use the moment object as described in the docs.
With Moment.js, this is simply:
moment().diff('2017-02-10T20:52:13.885Z', 'minutes') // 65
If you want partial minutes included, then pass true as a third parameter:
moment().diff('2017-02-10T20:52:13.885Z', 'minutes', true) // 65.04565

How to convert 12 hours datetime to timestamp with javascript

I have a datetime in following format 28/11/2015 09:41 PM and I want to convert it to epoch timestamp. How can I do that with javascript?
Additionally: I want to add and substracts 7200 seconds from that timestamp and convert it back to the original format. How can I do that? Is it necessary to convert datetime to timestamp first?
There is an awesome library available for that!
http://momentjs.com/
A great place to find information on JavaScript's built-in objects is the MDN, which has this article (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) on the datetime (or really just Date) object.
The way to get an epoch timestamp from a Date object is to use the getTime() function. It returns the number of milliseconds since 1 January, 1970.
var dateNow = Date.now();
var epochNow = dateNow.getTime();
You can then just add the seconds to it:
epochNow += (7200 * 1000); // * 1000 because it's in milliseconds
And then convert it back:
dateNow.setTime(epochNow);
Good luck!
NOTE
Beware inconsistencies in JavaScript Date implementations, especially in earlier versions of Internet Explorer. As some have noted, a good library like moment.js (http://momentjs.com/ ) is very helpful to prevent problems. However, if you are only using fully modern browsers or node, you shouldn't have as many problems.

Convert exact date to time ago using jquery - What format for the date?

I have a static page which will specify a hardcoded exact date. If the use has javascript, I want to then convert this hardcoded exact date into a "time ago".
For example:
3 hours ago
My question is, in what format of date will javascript be able to most efficiently convert to the time ago?
10/10/13
10.10.13
10th October 2013
101013
I would look at this post: https://stackoverflow.com/a/3177838/2895307
In it he just uses a javascript Date() as the parameter to the "timeSince()" function. To create a javascript Date from your hardcoded string you can use this format:
var d1 = new Date("October 13, 1975 11:13:00")
definitely unix timestamp is the best format for all date and time calculations, you can convert the results to a more readable format later.
the calculation is simple, you start with the timestamp of an event in the past, for example:
var anHourAgo = Date.now() - 3600000;
then you substract that from the current timestamp and get the number of milliseconds that have passed since that event
Date.now() - anHourAgo
then you can pass that to any function that will convert those milliseconds to hours, minutes and seconds, here's an example that takes seconds and returns an array with that info, and another function that pads those numbers with zeros
var zeroPad = function(n){
return n.toString().replace(/^(\d)$/,'0$1');
};
var formatSecs = function(s){
var r = [
Math.floor(s / 3600),
Math.floor(s%3600 / 60),
Math.floor((s%3600)%60)
];
r.push(zeroPad(r[0])+':'+zeroPad(r[1])+':'+zeroPad(r[2]));
return r;
};
the formatSecs function expects seconds instead of millseconds, you should divide by 1000 and round that number, then pass that number to the function
Math.round(Date.now() - anHourAgo) / 1000
Finally here's a working example of all that code in action:
http://codepen.io/DavidVValdez/pen/axHGj
i hope this helps, cheers!
The easiest thing to do would be to use Date.getTime().
This will give you the number of milliseconds since the Unix epoch and will make the math very simple.
Date.getTime

Categories