-1

I have a string like this - 2019-10-21 14:54:00

And five dropdown elements (for years, months, days, hours and minutes) like this:

<select id='selMonth'>
<option>01</option>
<option>02</option>
...
</select>

Now I need to place values from the string inside the corresponding elements, like this:

$('#selMonth').val(month-from-string);
$('#selHour').val(hour-from-string);

I tried to split the string, firstly by space, then first part by - and the second part by : but I hope there is a more natural way.

Any help?

qadenza
  • 9,025
  • 18
  • 73
  • 126
  • 1
    The date format from your string is already in a format javascript will understand: var date = new Date('2019-10-21 14:54:00'); console.log(date.getMonth()); console.log(date.getDate());... – François Huppé Jul 20 '19 at 08:15
  • @FrançoisHuppé - tried and getting `NaN` in console – qadenza Jul 20 '19 at 08:21

1 Answers1

1

You can parse the date into individual values using a regular expression:

const d = '2019-10-21 14:54:00';
const [, years, month, days, hours, minutes, seconds] = d.match(/(\d+)-(\d+)-(\d+)\s(\d+):(\d+):(\d+)/);

console.log(years, month, days, hours, minutes, seconds)
antonku
  • 7,377
  • 2
  • 15
  • 21