最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Convert Date in to custom format in javascript - Stack Overflow

programmeradmin1浏览0评论

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 :)

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 :)

Share Improve this question asked Dec 8, 2014 at 7:10 Manohar singhManohar singh 5094 silver badges27 bronze badges 2
  • What's the result you got with your attempts so far? – Felix Kling Commented Dec 8, 2014 at 7:12
  • I get 02:20 2014-18-11 , but i need to show result like 20:50 2014-18-11 – Manohar singh Commented Dec 8, 2014 at 7:34
Add a ment  | 

4 Answers 4

Reset to default 4

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

Example

<script src="http://momentjs./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

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")

Use this Demo JsFiddler

 var d = new Date,
        dformat = [ d.getHours().padLeft(), d.getMinutes().padLeft()].join(':')
                      + ' ' +
                  [d.getFullYear(), d.getDate().padLeft(), (d.getMonth()+1).padLeft()].join('-')
                  ;
Date.prototype._padding = function(v, w) {
    var f = "0000" + v;
    return ("0000" + v).substr(f.length-w, f.length)
}

Date.prototype.MyDateString = function() {
    return this._padding(this.getUTCHours(), 2) + ":" + this._padding(this.getUTCMinutes(), 2) + " " + this.getUTCFullYear() + "-" + this._padding(this.getUTCDate(), 2) + "-" + this._padding((this.getUTCMonth() + 1), 2);

}
console.log(new Date('2014-11-18T20:50:01.462Z').MyDateString())
console.log(new Date('2014-11-08T02:05:01.462Z').MyDateString())

getUTCMonth return 10, as the month is 0 based.

发布评论

评论列表(0)

  1. 暂无评论