FrontEnd Expert
FrontEnd Expert

Reputation: 5803

How to combine the two time and day value in moment js

I am using moment js and I am struggling with combining 2 inputs in one dateTime ,

enter image description here

I have 2 input values -

from 1st, I get day e.g. monday, tuesday, wednesday.. Saturday etc..

from 2nd, I get date time Wed May 26 2021 09:20:02 GMT+0530 (India Standard Time)

 dayDate  Wednesday
 timeValue  Wed May 26 2021 09:20:02 GMT+0530 (India Standard Time)

I want to combine both the value and have one date time and then need to convert that in milliseconds.

for e.g today is 26, user selected Saturday from one input and time from other, I have to take the next coming Saturday date and time from given second input.

How can I achieve that ?

Upvotes: 3

Views: 856

Answers (2)

Alex Nadin
Alex Nadin

Reputation: 46

In first you create a moment using the date you get from time picker, after you set the day of week with .day().

For convert the date in milliseconds you can use .format('x') (x is the Unix milliseconds timestamp)

function calculateDate () {
  const dayDate = "Saturday" // replace with your get element
  const timeValue = document.getElementById("timeValue").value;

  console.log('Complete date: ', moment(timeValue, 'HH:mm').day(dayDate).toDate());
  console.log('In Milliseconds', moment(timeValue, 'HH:mm').day(dayDate).format('x'));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

<input type="time" onchange="calculateDate()" id="timeValue">

If you get a complete Date Obejct from the time picker it will not necessary to specify the format in moment constructor, the code will become moment(timeValue).day(dayDate).format('x').

Upvotes: 3

User863
User863

Reputation: 20039

Using startOf('week') and day('Saturday')

Explanation

timeValue - Wed May 26 2021 11:35:27 GMT+0530 (India Standard Time)

startOf('week') - Sun May 23 2021 00:00:00 GMT+0530 (India Standard Time)

day('Saturday') - Sat May 29 2021 00:00:00 GMT+0530 (India Standard Time)

const dayDate = "Saturday"
const timeValue = new Date()

console.log(moment(timeValue).startOf('week').day(dayDate).toDate())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js" integrity="sha256-ZsWP0vT+akWmvEMkNYgZrPHKU9Ke8nYBPC3dqONp1mY=" crossorigin="anonymous"></script>

Upvotes: 2

Related Questions