簡體   English   中英

javascript將日期和時間轉換為特定格式

[英]javascript convert date and time into specific format

我是新手,想將2014-09-25T09:54:00轉換為9:54 AM Thu, 25th Sep

有人可以建議我用JavaScript做到這一點的方法嗎?

謝謝

正如Phrogz 在這里所說:

  1. 將字符串解析為JavaScript Date對象。
  2. 設置日期對象的格式即可

另請參閱: 為什么Date.parse給出不正確的結果? 以及如何格式化JavaScript日期問題。

例:

var myDate = new Date("2014-09-25T09:54:00")
var myString = myDate.customFormat("#h#:#mm# #AMPM# #DDD#, #D##th# #MMM#");

這里查看此代碼

here is a great JavaScript library that handles this very well, and only 5.5kb minified.

http://momentjs.com/

It looks something like this:


moment().format('MMMM Do YYYY, h:mm:ss a'); // February 25th 2013, 9:54:04 am
moment().subtract('days', 6).calendar(); // "last Tuesday at 9:53 AM"
You can also pass in dates as a String with a format, or a Date object.

var date = new Date();
moment(date); // same as calling moment() with no args

// Passing in a string date
moment("12-25-1995", "MM-DD-YYYY");
Also has great support for languages other then English, like, Russian, Japanese, Arabic, Spanish, etc..

我為你的情況開了個小提琴

它基於此處的出色教程,使格式化日期變得非常容易。

JavaScript代碼:

 var d_names = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"); var m_names = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"); var d = new Date(); var curr_date = d.getDate(); var sup = ""; if (curr_date == 1 || curr_date == 21 || curr_date ==31) { sup = "st"; } else if (curr_date == 2 || curr_date == 22) { sup = "nd"; } else if (curr_date == 3 || curr_date == 23) { sup = "rd"; } else { sup = "th"; } var a_p = ""; var curr_hour = d.getHours(); if (curr_hour < 12) { a_p = "AM"; } else { a_p = "PM"; } if (curr_hour == 0) { curr_hour = 12; } if (curr_hour > 12) { curr_hour = curr_hour - 12; } var curr_day = d.getDay(); var curr_min = d.getMinutes(); var curr_month = d.getMonth(); var curr_year = d.getFullYear(); var curr_hour = d.getHours(); alert((curr_hour + " : " + curr_min + " " + a_p)+ (" " + d_names[curr_day] + ", " + curr_date + sup + " " + m_names[curr_month] /* +" " + curr_year */)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM