try123
try123

Reputation: 15

How can I convert the value I get with datetimepicker to date and time?

var innerDate = document.getElementById('datetimepicker3').value;

The format I get from this line is: innerDate: "2021/07/07 14:00"

But I need to parse the date and time information here. How can I convert Start Date and Start Time into two separate variables?

Upvotes: 1

Views: 1186

Answers (3)

McBeelen
McBeelen

Reputation: 430

I would recommend to parse that string with moments.js and then depending on your needs either get the individual parts for calculations or apply needed formatting

Example available at https://jsfiddle.net/Ly6qen3w/

let innerDateInput = "2021/07/07 14:00";
let innerDateMoment = moment(innerDateInput, "YYYY/MM/DD hh:mm");

console.log("Date:"+innerDateMoment.format("YYYY-MM-DD"));
console.log("Time:"+innerDateMoment.format("hh:mm"));

Upvotes: 1

Amila Senadheera
Amila Senadheera

Reputation: 13235

Try this:

var innerDate = new Date(document.getElementById('datetimepicker3').value)

Or you can attach an event handler to get the date whenever it changes

<script type="text/javascript">
   $("#datetimepicker3").on("dp.change", function (e) {
        let date = e.date;
        console.log(date);
        // no need to convert to a date
   });
</script>

Upvotes: 0

Sanjeev_gupta2812
Sanjeev_gupta2812

Reputation: 236

You can simple get that in different variable using various methods that are provided by JavaScript to get everything.

You can do is(id it's a date object else you have to convert it to date object)

let startDate = new Date(innerDate).getDate() + "/" + new Date(innerDate).getMonth() + "/" + new Date(innerDate).getFullYear();

let startTime = new Date("2021/07/07 14:00").getHours() +":"+ new Date("2021/07/07 14:00").getMinutes()

If you want something else you can retrieve that too with methods such as milliseconds,UFC time etc.

If you find this messy I would suggest you to use moment.js. https://momentjs.com/

Upvotes: 0

Related Questions