最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - moment js change the date portion of a datetime - Stack Overflow

programmeradmin1浏览0评论

Using the moment.js library say i have a datetime with today's date and i would like to replace only the date part of the datetime with another value and keep the time portion the same

I don't want to subtract or add days etc - i have a 3rd party time picker that when you select a time it creates a datetime that is always the current day. I need to send back to server a different datetime - the date is different but keep the time portion from the picker.

example code:

let myDate = "2019-03-15T00:00:00"
let selectedDateTime = "2019-04-04T12:30:00" 

expected result would be:

"2019-03-15T12:30:00"

Thank you

Using the moment.js library say i have a datetime with today's date and i would like to replace only the date part of the datetime with another value and keep the time portion the same

I don't want to subtract or add days etc - i have a 3rd party time picker that when you select a time it creates a datetime that is always the current day. I need to send back to server a different datetime - the date is different but keep the time portion from the picker.

example code:

let myDate = "2019-03-15T00:00:00"
let selectedDateTime = "2019-04-04T12:30:00" 

expected result would be:

"2019-03-15T12:30:00"

Thank you

Share Improve this question edited Apr 4, 2019 at 15:18 JimmyShoe asked Apr 4, 2019 at 15:11 JimmyShoeJimmyShoe 2,2995 gold badges25 silver badges45 bronze badges 1
  • OK so you want the day of the first date, but the time of the second date? It should be fairly easy with a tool like MomentJS. It has plenty of useful methods to get and set days, hours, minutes and seconds. All you have to do is get the time from the second date, and set it to the first date. – Jeremy Thille Commented Apr 4, 2019 at 15:22
Add a ment  | 

1 Answer 1

Reset to default 8

The following should solve your problem:

let myDate = moment("2019-03-15T00:00:00")
let selectedDateTime = moment("2019-04-04T12:30:00")

selectedDateTime.date(myDate.date());
selectedDateTime.month(myDate.month());
selectedDateTime.year(myDate.year());

As @JeremyThille suggested, you should take a look at the documentation.

发布评论

评论列表(0)

  1. 暂无评论