使用Javascript格式化日期时间

vip*_*yar 10 html javascript

我有一个日期/时间字符串,2012-01-13 04:37:20但我想将其转换为dd-mm-yyyy hh:mm,我该怎么做?

我使用以下代码,但它抛出异常.

var now = "2012-01-13 04:37:20";
var dd = now.toLocaleDateString() + " " + now.toLocaleTimeString();
alert(dd);
Run Code Online (Sandbox Code Playgroud)

Sel*_*gam 9

您可以执行简单的字符串操作并创建js日期对象.请参阅下面的函数,该函数以格式// yyyy-mm-dd hh:mm:ss接受日期

DEMO在这里

function toJSDate (dateTime) {

var dateTime = dateTime.split(" ");//dateTime[0] = date, dateTime[1] = time

var date = dateTime[0].split("-");
var time = dateTime[1].split(":");

//(year, month, day, hours, minutes, seconds, milliseconds)
return new Date(date[0], date[1], date[2], time[0], time[1], time[2], 0);

}
Run Code Online (Sandbox Code Playgroud)

  • 'date [1]`应该是'date [1] - 1`以正确输出月份. (7认同)

giu*_*ppe 7

JavaSCript中最好的日期时间处理库就是时刻.

moment().format('MMMM Do YYYY, h:mm:ss a');
Run Code Online (Sandbox Code Playgroud)


Juk*_*ela 5

使用简单的字符串操作(如@SKS所建议)或使用库.后者更灵活,可让您轻松更改输入或输出格式.例如,使用Globalize.js库,您可以编写:

var dd = Globalize.parseDate(now, "yyyy-MM-dd HH:mm:ss");
dd = Globalize.format(dd, "dd-MM-yyyy HH:mm");
Run Code Online (Sandbox Code Playgroud)

但请注意,诸如"dd-mm-yyyy hh:mm"之类的格式令人困惑 - 它既不是标准ISO格式也不是任何本地化(语言相关)格式.除了明确指定的格式之外,Globalize.js库还允许您使用预定义的语言相关格式.

请注意,JavaScript中的内置日期和时间解析和格式化例程是依赖于实现的.使用它们意味着不可移植的代码.例如,不能保证new Date()将接受您输入的格式,而toLocaleDateString()以某种依赖于语言环境的格式写入日期,这可以是任何事情.


thd*_*oan 5

如果不需要Moment.js之类的库提供的所有功能,则可以使用我的strftime端口。它是轻量级的(与Moment.js 2.15.0相比,最小化为1.35 KB与57.9 KB),并提供的大多数功能strftime()

/* Port of strftime(). Compatibility notes:
 *
 * %c - formatted string is slightly different
 * %D - not implemented (use "%m/%d/%y" or "%d/%m/%y")
 * %e - space is not added
 * %E - not implemented
 * %h - not implemented (use "%b")
 * %k - space is not added
 * %n - not implemented (use "\n")
 * %O - not implemented
 * %r - not implemented (use "%I:%M:%S %p")
 * %R - not implemented (use "%H:%M")
 * %t - not implemented (use "\t")
 * %T - not implemented (use "%H:%M:%S")
 * %U - not implemented
 * %W - not implemented
 * %+ - not implemented
 * %% - not implemented (use "%")
 *
 * strftime() reference:
 * http://man7.org/linux/man-pages/man3/strftime.3.html
 *
 * Day of year (%j) code based on Joe Orost's answer:
 * http://stackoverflow.com/questions/8619879/javascript-calculate-the-day-of-the-year-1-366
 *
 * Week number (%V) code based on Taco van den Broek's prototype:
 * http://techblog.procurios.nl/k/news/view/33796/14863/calculate-iso-8601-week-and-year-in-javascript.html
 */
function strftime(sFormat, date) {
  if (!(date instanceof Date)) date = new Date();
  var nDay = date.getDay(),
    nDate = date.getDate(),
    nMonth = date.getMonth(),
    nYear = date.getFullYear(),
    nHour = date.getHours(),
    aDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
    aMonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    aDayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],
    isLeapYear = function() {
      return (nYear%4===0 && nYear%100!==0) || nYear%400===0;
    },
    getThursday = function() {
      var target = new Date(date);
      target.setDate(nDate - ((nDay+6)%7) + 3);
      return target;
    },
    zeroPad = function(nNum, nPad) {
      return ('' + (Math.pow(10, nPad) + nNum)).slice(1);
    };
  return sFormat.replace(/%[a-z]/gi, function(sMatch) {
    return {
      '%a': aDays[nDay].slice(0,3),
      '%A': aDays[nDay],
      '%b': aMonths[nMonth].slice(0,3),
      '%B': aMonths[nMonth],
      '%c': date.toUTCString(),
      '%C': Math.floor(nYear/100),
      '%d': zeroPad(nDate, 2),
      '%e': nDate,
      '%F': date.toISOString().slice(0,10),
      '%G': getThursday().getFullYear(),
      '%g': ('' + getThursday().getFullYear()).slice(2),
      '%H': zeroPad(nHour, 2),
      '%I': zeroPad((nHour+11)%12 + 1, 2),
      '%j': zeroPad(aDayCount[nMonth] + nDate + ((nMonth>1 && isLeapYear()) ? 1 : 0), 3),
      '%k': '' + nHour,
      '%l': (nHour+11)%12 + 1,
      '%m': zeroPad(nMonth + 1, 2),
      '%M': zeroPad(date.getMinutes(), 2),
      '%p': (nHour<12) ? 'AM' : 'PM',
      '%P': (nHour<12) ? 'am' : 'pm',
      '%s': Math.round(date.getTime()/1000),
      '%S': zeroPad(date.getSeconds(), 2),
      '%u': nDay || 7,
      '%V': (function() {
              var target = getThursday(),
                n1stThu = target.valueOf();
              target.setMonth(0, 1);
              var nJan1 = target.getDay();
              if (nJan1!==4) target.setMonth(0, 1 + ((4-nJan1)+7)%7);
              return zeroPad(1 + Math.ceil((n1stThu-target)/604800000), 2);
            })(),
      '%w': '' + nDay,
      '%x': date.toLocaleDateString(),
      '%X': date.toLocaleTimeString(),
      '%y': ('' + nYear).slice(2),
      '%Y': nYear,
      '%z': date.toTimeString().replace(/.+GMT([+-]\d+).+/, '$1'),
      '%Z': date.toTimeString().replace(/.+\((.+?)\)$/, '$1')
    }[sMatch] || sMatch;
  });
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

// Returns "15-09-2016 16:20"
strftime('%d-%m-%Y %H:%M');

// You can optionally pass it a Date object
// Returns "01-01-2016 21:30"
strftime('%d-%m-%Y %H:%M', new Date('Jan 1, 2016 9:30 PM'));
Run Code Online (Sandbox Code Playgroud)

最新的代码在这里可用:https : //github.com/thdoan/strftime