Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Date in to custom format in javascript

Tags:

javascript

I have a Date format like this

 2014-11-18T20:50:01.462Z

I need to convert to the custom format like "20:50 2014-18-11" using Javascript date function

I need result like

20:50 2014-18-11

How to get this , Thanks in Advance :)

like image 568
Manohar singh Avatar asked Aug 04 '26 01:08

Manohar singh


2 Answers

Assuming you're able to include new libraries on your project, I'd highly recommend moment.js (MIT license) instead of writing this yourself. It solves problems like zero padding etc. for you.

Example

<script src="http://momentjs.com/downloads/moment.min.js"></script>
<script>
// Use an existing date object
var date = new Date("2014-11-18T20:50:01.462Z");
console.log(moment(date).format('HH:mm YYYY-DD-MM'));

// or use string directly
console.log(moment.utc("2014-11-18T20:50:01.462Z").format('HH:mm YYYY-DD-MM'));
</script>

Note by default moment will use your current timezone for output, this can be overridden using the zone() function

console.log(moment.utc("2014-11-18T20:50:01.462Z").zone(0).format('HH:mm YYYY-DD-MM'));
console.log(moment.utc("2014-11-18T20:50:01.462Z").zone('UTC+05:30').format('HH:mm YYYY-DD-MM'));

Output

20:50 2014-18-11
like image 181
Adam Avatar answered Aug 05 '26 14:08

Adam


Try moment js its very nice plugin to play around dates and times

so all you need to do is import moment js and put this line in your js code using moment.js will also help you in future for your code

moment.utc("2014-11-18T20:50:01.462Z").format("HH:mm YYYY-DD-MM")
like image 40
Madhav Avatar answered Aug 05 '26 15:08

Madhav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!