Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Seconds/ Milliseconds from Date convert to ISO String

I have a date object that I want to

  1. remove the miliseconds/or set to 0
  2. remove the seconds/or set to 0
  3. Convert to ISO string

For example:

var date = new Date(); //Wed Mar 02 2016 16:54:13 GMT-0500 (EST)  var stringDate = moment(date).toISOString(); //2016-03-02T21:54:13.537Z 

But what I really want in the end is

stringDate = '2016-03-02T21:54:00.000Z' 
like image 522
tester123 Avatar asked Mar 02 '16 21:03

tester123


People also ask

How to remove milliseconds from timestamp in JavaScript?

Use the setSeconds() method to remove the seconds and milliseconds from a date, e.g. date. setSeconds(0, 0) . The setSeconds method takes the seconds and milliseconds as parameters and sets the provided values on the date. Copied!

How do I remove T and Z from timestamp?

To remove the T and Z characters from an ISO date in JavaScript, we first need to have the date in ISO format. If you don't have it already, you can convert it to ISO using the toISOString function on a Date object. This will get rid of both T and Z, resulting in "2022-06-22 07:54:52.657".

How do I convert ISO to timestamp?

Use the getTime() method to convert an ISO date to a timestamp, e.g. new Date(isoStr). getTime() . The getTime method returns the number of milliseconds since the Unix Epoch and always uses UTC for time representation.


1 Answers

While this is easily solvable with plain JavaScript (see RobG's answer), I wanted to show you the Moment.js solution since you tagged your questions as "momentjs":

moment().seconds(0).milliseconds(0).toISOString(); 

This gives you the current datetime, without seconds or milliseconds.

Working example: http://jsbin.com/bemalapuyi/edit?html,js,output

From the docs: http://momentjs.com/docs/#/get-set/

like image 146
jszobody Avatar answered Oct 11 '22 02:10

jszobody