Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change time with moment.js?

Tags:

I want to change some time using moment.js.

I have next time: Tue May 16 2017 15:34:23 GMT+0300 (FLE Daylight Time), and I want to change it to 11.11 for example.

And time should be Tue May 16 2017 11:11:23 GMT+0300 (FLE Daylight Time).

How can i implement this?

like image 335
Max K Avatar asked May 16 '17 12:05

Max K


People also ask

What is moment () hour ()?

The moment(). hour() Method is used to get the hours from the current time or to set the hours. Syntax: moment().hour(); or. moment().

How do you add hours to a moment?

To add hours to a parsed moment date with JavaScript, we can use the add method. to add 5 hours to the moment object parsed from myDate . We call add with 5 and 'hours' to add 5 hours. And then we call format with a format string to return the datetime stored in the moment object.


1 Answers

As stated by others in the comment, you have to:

  1. Parse your input as moment object, you can use:
    • moment(String, String) if your input is a String
    • moment(Date) if your input is a JavaScript Date
  2. Use moment setters (e.g. set) to set both hours and minutes.

You can use format() to display your moment object. If you need to convert moment object to JavaScript date you can use toDate() method.

Here live sample:

var dateString = 'Tue May 16 2017 15:34:23 GMT+0300 (FLE Daylight Time)';  var m = moment(dateString, 'ddd MMM D YYYY HH:mm:ss ZZ');  // Use moment(Date) if your input is a JS Date  //var m = moment(date);  m.set({h: 11, m: 11});  console.log(m.format());  console.log(m.toDate().toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
like image 143
VincenzoC Avatar answered Sep 24 '22 12:09

VincenzoC