如何使用javascript格式化此日期/时间?

时间:2019-06-02 19:28:18

标签: javascript

我如何转换

2018-05-07T17:51:17.258000-07:00

进入:

May 7, 2018, 5:51 p.m.

使用javascript。

我对javascript完全陌生,无法解决。

3 个答案:

答案 0 :(得分:1)

您可以使用像Moment.js这样的库:https://momentjs.com/

const date = moment('018-05-07T17:51:17.258000-07:00').format('LLL');

答案 1 :(得分:1)

您可以将Date#toLocaleString与现代浏览器中可用的选项一起使用。

您想要的格式对应于加拿大的语言环境,该语言环境通过在“ p.m”中加点来与美国语言环境区分开。然后将“ PM”小写:

var someDate = new Date();
var str = someDate.toLocaleString('en-CA', { 
    month: "long",
    day: "numeric",
    year: "numeric",
    hour: "numeric", 
    minute: "2-digit"
});

console.log(str);

答案 2 :(得分:0)

有很多选择。

  1. (轻松)使用JavaScript库

签出https://momentjs.com 他们有一个非常易于使用的.format方法

moment('2018-05-07T17:51:17').format('MMM DD, YYYY, h:mm a')
  1. (轻松)使用系统日期格式

您可以选择使用 .toLocaleString(),而不是使用自定义格式,该格式会将日期格式化为所运行计算机的语言设置。

new Date('2018-05-07T17:51:17').toLocaleString();
  1. (复杂)用香草JavaScript编写自定义格式方法。

JS本身在处理日期时非常复杂,但绝对有可能。建议阅读Date对象(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Date.prototype_Methods)上所有方法的文档,因为某些方法返回的结果可能与JavaScript初学者所得到的结果略有不同。

查看这个小提琴:https://jsfiddle.net/3graf72m/ 我添加了一些评论来解释我做了什么

const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

document.body.innerHTML = getFormattedDate(new Date('2018-05-07T17:51:17'));

/**
 * Get the formatted date
 * @param {Date} date
 * @returns {String}
 */
function getFormattedDate(date) {
  const month = getMonthName(date);
  const day = getNumericDay(date);
  const year = getYear(date);

  let hour = (date.getHours() + 12) % 12;
  if (hour === 0) {
    hour = 12;
  }

  let minute = date.getMinutes();
  if (minute.length === 1) {
    minute = `0${minute}`;
  }

    const isAm = date.getHours() < 12;
  return `${month} ${day}, ${hour}:${minute} ${isAm ? 'a.m.' : 'p.m.'}`;
}

/**
 * Get the name of the month
 * @param {Date} date
 * @returns {String}
 */
function getMonthName(date) {
  // getMonth returns 0-based value
    const zeroBasedMonthInt = date.getMonth();
    return MONTHS[zeroBasedMonthInt];
}

/**
 * Get number value of the day of the month of a date
 * @param {Date} date
 * @returns {Number}
 */
function getNumericDay(date) {
  // .getDay returns zero-based day in week (starting from Sunday)
  // .getDate returns day of month (starting with 1)
    return date.getDate();
}

/**
 * Get the full year of a date
 * @param {Date} date
 * @returns {Number}
 */
function getYear(date) {
  // getYear returns year since 1900
    // getFullYear returns year (starting from 0)
    return date.getFullYear();
}