yusry
yusry

Reputation: 148

Convert SQL datetime to show in input type datetime local

I have a datetime string which is being retrieved from controller in the following format:

dd-MM-yyyy hh:mm:ss a
3/1/2018 4:02:00 PM

I want to show it in input type datetime-local. So I need to convert the datetime in to this format:

yyyy-MM-DDTHH:mm
2018-01-03T16:02

I try to use this code at first which will give an output as js format then use a function to format it back. But it mistakenly read month as day and day as month. Which means the output will show like this 2018-03-01T16:02.

var date_test = new Date("3/1/2018 4:02:00 PM".replace(/-/g,"/"));

Is there another way to convert this correctly?

Upvotes: 2

Views: 1434

Answers (2)

Ctznkane525
Ctznkane525

Reputation: 7465

Using moment.js. Great library:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.7.0/moment.min.js"></script>
<script type="text/javascript">

var dateString = "3/1/2018 4:02:00 PM";
var currentDate = moment(dateString, "M/D/YYYY h:mm:ss a");
document.write(currentDate.format("YYYY-MM-DDTHH:mm"))
</script>

Upvotes: 0

user1063108
user1063108

Reputation: 712

Since you already know the format

dd-MM-yyyy hh:mm:ss a
3/1/2018 4:02:00 PM

why not just split the string correctly(date part and then time part) and finally just create new date object using yyyy,MM,dd etc?

Upvotes: 1

Related Questions