-1

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.

WildThing
  • 969
  • 1
  • 12
  • 30
  • In plain JS, you could replace the offset with Z, parse it, do everything in UTC, then use *toISOString* and replace the Z with the offset again. – RobG Sep 27 '21 at 13:58
  • could you please demonstrate how to do that? – WildThing Sep 27 '21 at 14:32

1 Answers1

1

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>
Tuan Dao
  • 2,647
  • 1
  • 10
  • 20