Home > Net >  Update Date or time from an ISO string moment JS library
Update Date or time from an ISO string moment JS library

Time:09-27

What is the simplest way to update a day or time from a given string. For example I have a moment date in the following format.

start: '2021-09-30T06:30:00-04:00'

expected output: '2021-09-29T06:30:00-04:00'

Now I want to keep the current time, but replace the date to 29th or 28th, or change the month. How would I do that, I am allowed to use the native JS Date or moment library but the point is the rest of the string must be the same, It should definitely keep the timezone offset.

CodePudding user response:

You can use

moment().set(String, Int);
moment().set(Object(String, Int));

https://momentjs.com/docs/#/get-set/set/

var dateStr = '2021-09-30T06:30:00-04:00';
var oldDate = moment(dateStr);

// Parse timezone offset
var utcOffset = moment.parseZone(dateStr).utcOffset();

var changedDate = oldDate.set("date", 29);
console.log(changedDate.utcOffset(utcOffset).format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8 M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

  • Related