使用 Javascript 格式化日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8847109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:46:35  来源:igfitidea点击:

Formatting the date time with Javascript

javascripthtml

提问by vipin katiyar

I have a date/time string like 2012-01-13 04:37:20but I want to convert it to dd-mm-yyyy hh:mm, how can i do this?

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

I am using the following code but it throws an exception.

我正在使用以下代码,但它引发了异常。

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

采纳答案by Selvakumar Arumugam

You can do a simple string manipulation and create js date object. See function below, which accepts date in format //yyyy-mm-dd hh:mm:ss

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

DEMOhere

演示在这里

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

}

回答by giuseppe

The best date-time handling lib in JavaSCript is moment.

JavaSCRipt 中最好的日期时间处理库是moment。

moment().format('MMMM Do YYYY, h:mm:ss a');

回答by thdoan

If you don't need all the features that a library like Moment.jsprovides, then you can use my port of strftime. It's lightweight (1.35 KB vs. 57.9 KB minified compared to Moment.js 2.15.0) and provides most of the functionality of strftime().

如果您不需要像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+).+/, ''),
      '%Z': date.toTimeString().replace(/.+\((.+?)\)$/, '')
    }[sMatch] || sMatch;
  });
}

Sample usage:

示例用法:

// 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'));

The latest code is available here: https://github.com/thdoan/strftime

最新代码可在此处获得:https: //github.com/thdoan/strftime

回答by Jukka K. Korpela

Use either simple string manipulation (as suggested by @SKS) or use a library. The latter is more flexible and lets you change the input or output format easily. For example, using the Globalize.jslibrary, you would write:

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

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

Note however that formats such as "dd-mm-yyyy hh:mm" are confusing – it is neither a standard ISO format nor any localized (language-dependent) format. The Globalize.js library lets you use predefined language-dependent formats in addition to explicitly specified formats.

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

Note that the built-in date and time parsing and formatting routines in JavaScript are implementation-dependent. Using them means non-portable code. For example, there is no guarantee that new Date()will accept the format you have as input, and toLocaleDateString() writes the date in some locale-dependent format, which can be just about anything.

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

回答by PartTimeIndie

I think it is best to use the Intl.DateTimeFormatclass.

我认为最好使用Intl.DateTimeFormat类。

The usage is fairly straightforward. You can not enter a pattern as you want to, but it will give you the results you want.

用法相当简单。您不能随意输入模式,但它会给您想要的结果。

Here is an example on how to use it:

以下是有关如何使用它的示例:

public formatDate(date : Date) : string{
    var options = {  year: 'numeric', month: 'short', day: 'numeric' };
    return new Intl.DateTimeFormat('de-DE', options).format(date);
}

If you really want to enter a DateTimeFormat string, it would be easy enough to write a function which parses the string using Regex, but I don't think it is needed.

如果你真的想输入一个 DateTimeFormat 字符串,那么编写一个使用 Regex 解析字符串的函数就很容易了,但我认为不需要它。

For further Information go here:

欲了解更多信息,请访问:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat

回答by Iman Bahrampour

For working with DateTimes in javascript it's better to use the 'Intl.DateTimeFormat' as follow:

要在 javascript 中使用 DateTimes,最好使用“Intl.DateTimeFormat”,如下所示:

var date = new Date('2012-01-13 14:37:20');
var options = { year: 'numeric', month: '2-digit', day: '2-digit',
hour:'2-digit', minute: '2-digit',hour12: false};
console.log(new Intl.DateTimeFormat('en-US', options).format(date).replace(/\//g,'-').replace(',',''));

Result: "01-13-2012 14:37"

结果:“01-13-2012 14:37”

The date and time formats can be customized with options argument.

可以使用 options 参数自定义日期和时间格式。

Check Online

在线查询

回答by user3117708

a small function , as follow:

一个小函数,如下:

var formatTime = function(time, format){
time = typeof time == 'number' ? new Date(time) : time;
format = format || 'yyyy-mm-dd hh:MM:ss';
var year = time.getFullYear();
var month = time.getMonth() + 1;
var date = time.getDate();
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
var add0 = function(t){return t < 10 ? '0' + t : t}
var replaceMent = {
    'yyyy': year,
    'mm': add0(month),
    'm': month,
    'dd': add0(date),
    'd': date,
    'hh': add0(hours),
    'h': hours,
    'MM': add0(minutes),
    'M': minutes,
    'ss': add0(seconds),
    's': seconds
}
for( var k in replaceMent ){
    format = format.replace(k, replaceMent[k]);
}
return format;

}

}

回答by Tom

Love one liners - local date SPACE time DOT milliseconds / IIFE:

爱一个班轮 - 本地日期空间时间 DOT 毫秒 / IIFE:

// simpler, but milliseconds not padded
console.log(
(function(d){return d.toLocaleDateString() + ' ' + d.toLocaleTimeString() + '.' + d.getMilliseconds()})(new Date())
)

// including millis padding
console.log(
(function(d){return d.toLocaleDateString() + ' ' + d.toLocaleTimeString() + '.' + (d.getMilliseconds()+1000+'').substr(1)})(new Date())
)

回答by Kodie Grantham

Easily accomplished by my date-shortcodepackage:

通过我的日期短代码包轻松完成:

const dateShortcode = require('date-shortcode')
dateShortcode.parse('{DD-MM-YYYY hh:mm}', '2012-01-13 04:37:20')
//=> '13-01-2012 04:37'

回答by RAY

With Jquery, you steal datepicker's feature like that:

使用 Jquery,您可以像这样窃取 datepicker 的功能:

$.datepicker.formatDate( "dd-M-yy", new Date())