How can the Moment.js get the timestamp? - javascript

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

Related

Issues parsing a string-date React/JS

For example, I have this string "2020-09-09T21:00:14.114-04:00"
I grab this from my database and in its current form, it is a string. my goal is to have it display
4 PM instead of the long string of jibberish
is it possible to accomplish this?
I was thinking of possibly creating a new date object like
let test = new Date('2020-09-09T21:00:14.114-04:00').
but I'm stuck at the parsing and formatting part. it would be better to have this be done while the current state is a string but I don't think that this would be possible
edit: i would like the desired output to be the hour:minute and then am/pm
ex 10:15pm
You can do that by parsing the date from your database using Date.parse().
Then you can get the time or whatever you need using date.toLocalTimeString() in your case.
let dateUnix = Date.parse('2020-09-09T21:00:14.114-04:00');
const time = new Date(dateUnix).toLocaleTimeString();
console.log(time); // --> "4:00:14 AM"
The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).
Here's some useful resources MDN Date.parse()
MDN Date.toLocalTimeString()
You can do as following way.new Date() is used to get the current date and time.
var today = new Date();
var time = today.getHours();
if(time>12){
var new_time= time % 12;
}
else{
var new_time= time;
}

how to get only time from date in ISO formate

How to extract only time from the date which is present in ISO format?
I tried this:
var d = new Date('1970-01-15T03:32:12.000Z'); //ISO-8601 formatted date returned from server
console.log(d.getTime());// 1222332000
Expected op is : 03:32:12
Since your server returns an ISO-8601 formatted date which has a predefined format, you can convert it to ISO string using toISOString() and then get the substring of the time value:
var d = new Date('1970-01-15T03:32:12.000Z');
console.log(d.toISOString().substr(11,8));
Date.getTime() returns the time in UNIX epoch format.
https://en.wikipedia.org/wiki/Unix_time
To access only the parameters you are interested in, you can use Date.getMinutes(), Date.getMinutes(), etc. See docs on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Note: Do not forget to spend one thought on time zones when you work with Date
's time, especially when your app runs in different regions.
You have to manually build the time string using Date.prototype methods: getHours, getMinutes and getSeconds
Or use moment.js library.
Date.getTime() gives you the unix timestamp, which is the number of seconds since january 1st 1970;
The getTime() method returns the numeric value corresponding to the time for the specified date according to universal time.
from MDN
You need to format the date yourself, either by concatenating the output of the Date.getHours(), Date.getMinutes() and Date.getSeconds() methods, or by using one of the predefined formatting functions, like Date.toTimeString(). Checkout the docs to pick your choice.
You can use getHours(),getMinutes() and getSecondes(). Then you can use it with strings or objects.
Try the following:
d.toTimeString().split(' ')[0]
You can use moment.js to parse whatever format you like.
If you think moment.js is too big, there's another library call dayjs. The same fashion API but just 2KB. (Unfortunately, you can't do UTC time with dayjs yet.)
Update: Thanks kun for notifying the updates. You can now use UTC with dayjs plugin since v1.8.9.
var d = new Date('1970-01-15T03:32:12.000Z');
console.log(moment(d).utc().format('HH:mm:ss'));
dayjs.extend(dayjs_plugin_utc)
console.log(dayjs(d).utc().format('HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.9/dayjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.9/plugin/utc.js"></script>

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 substract current utc time from php iso utc?

I want to get current time in UTC, substract it from ISO UTC string which I'm getting from backend in the following format: 2016-11-29T17:53:29+0000 (ISO 8601 date, i guess?) and get an answer in milliseconds.
What is the shortest way to do it in javascript? I'm using angular 2 and typescript frontend.
You can get the current time using:
var now = Date.now()
And convert the string to a milliseconds timestamp using:
var ts = (new Date('2016-11-29T17:53:29+0000')).getTime()
And then subtract the values:
var diff = ts - now

how to convert a string to a Unix timestamp in 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

Categories