如何在javascript中获取此dateformat

时间:2018-01-02 13:41:56

标签: javascript date

目前我有这种格式的日期

cdate = 2016-06-29 23:45:42

我需要将此日期转换为此格式

Wed 06/29/2016 11:45 PM

new Date(cdate)正在给我

Wed Jun 29 2016 23:45:42 GMT+0530 (India Standard Time)

3 个答案:

答案 0 :(得分:2)

console.log(moment("2016-06-29 23:45:42").format("ddd MM/DD/YYYY hh:mm A"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.js"></script>

您可以使用momentjs使用format("ddd MM/DD/YYYY hh:mm A")

格式化日期

答案 1 :(得分:0)

更复杂,但没有第三方库:

let formatted = (d => {
  // Convert the date to JS string representation and split on space
  let [dow, mn, dom, year, time] = new Date(d).toString().split(/\s/);
  // Extract the month from the original string
  let [mon] = d.split('-')[0];
  // Put month, day, year in desired format
  let datestring = `${mon}/${dom}/${year}`;
  // Extract the time parts, convert to numbers
  let [hr, min, sec] = time.split(':').map(Number);
  let [hour, am] = hr > 11 ? [hr - 12, 'PM'] : [hr, 'AM'];
  return `${dow} ${datestring} ${hour}:${min} ${am}`;
})(cdate);

console.log(formatted); // Wed 2/29/2016 11:45 PM

如果你需要用零填充月/日,你可以使用这个辅助函数:

let padNumber = nstring => +nstring < 10 ? `0${nstring}` : nstring;

答案 2 :(得分:0)

如果您不想使用任何库,可以使用Intl。它没有DOW支持,但你可以很容易地得到它。

const date = new Date(2016, 05, 29, 11, 45);
const dow = ['Sunday','Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

console.log(`${dow[date.getDay()]} ${new Intl.DateTimeFormat('en-US', { hour: 'numeric', minute: 'numeric', month: 'numeric', year: 'numeric', day: 'numeric' }).format(date)}`);

// or with short weekday name in the host default language

console.log(`${date.toLocaleString(undefined, {weekday:'short'})} ${date.toLocaleString(undefined, {hour: '2-digit', minute: '2-digit', month: '2-digit', year: 'numeric', day: '2-digit'})}`);