如何格式化JavaScript日期

leo*_*ora 1945 javascript date date-format time-format

如何格式化要打印的JavaScript日期对象10-Aug-2010

小智 1762

使用 toLocaleDateString()

toLocaleDateString()方法返回一个字符串,其中包含日期日期部分的语言敏感表示.locales和options参数允许应用程序指定应使用其格式约定的语言,并允许自定义函数的行为.

您可以在不同键的选项中传递的值:

  1. day:当天
    的代表.
    可能的值为"数字","2位".
  2. 工作日:工作日
    的代表.
    可能的值是"窄","短","长".
  3. 年:年份
    的代表.
    可能的值为"数字","2位".
  4. month:月份
    的代表.
    可能的值是"数字","2位","窄","短","长".
  5. 小时:小时
    的表示.
    可能的值为"数字","2位".
  6. 分钟:分钟 的表示.
    可能的值为"数字","2位".
  7. 第二:第二个
    的表示.
    可能的值为"数字",2位数字".

所有这些键都是可选的.您可以根据需要更改选项值的数量,这也将反映每个日期时间项的存在.

注意:如果您只想配置内容选项,但仍使用当前区域设置,则传递null第一个参数将导致错误.请undefined改用.

对于不同的语言:

  1. "en-US":英语
  2. "hi-IN":对于印地语
  3. "ja-JP":对于日本人

您可以使用更多语言选项.

例如

var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var today  = new Date();

console.log(today.toLocaleDateString("en-US")); // 9/17/2016
console.log(today.toLocaleDateString("en-US", options)); // Saturday, September 17, 2016
console.log(today.toLocaleDateString("hi-IN", options)); // ??????, 17 ?????? 2016
Run Code Online (Sandbox Code Playgroud)

您也可以将此toLocaleString()方法用于相同目的.唯一的区别是此功能提供了不传递任何选项的时间.

// Example
9/17/2016, 1:21:34 PM
Run Code Online (Sandbox Code Playgroud)

参考文献:

  • 几乎即将使用`moment.js`作为一种简单的格式.幸运的是,进行了额外的谷歌搜索并发现已有本机API执行此操作.保存了外部依赖.真棒! (31认同)
  • 似乎这个答案应该是最好的"当前"答案.还使用选项"hour12:true"来使用12小时与24小时格式.也许应该在答案中添加到您的摘要列表中. (17认同)
  • @Iarwa1n 这个答案没有提到,但您可以使用 toLocaleDateString 仅返回某些部分,然后您可以根据需要加入这些部分。检查下面我的答案。`date.toLocaleDateString("en-US", { day: 'numeric' }) + "-"+ date.toLocaleDateString("en-US", { Month: 'short' }) + "-" + date.toLocaleDateString ("en-US", {year: 'numeric' })` 应该给出 `16-Nov-2019` (15认同)
  • 我没有得到这个答案的赞成.它没有解决问题中的问题.(即给我一个看起来像2010年8月10日的日期).使用toLocaleDateString()非常困难.date.format库似乎是更好的解决方案(至少对于Node用户而言) (10认同)
  • @KVij - 这是一种格式化日期的非常低效的方法,特别是考虑到有一个 [*formatToParts* 方法](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects /Intl/DateTimeFormat/formatToParts) 返回对象数组中的所有部分。 (6认同)
  • date1.toLocaleString('en-US')。replace(',',''); 返回此“ 9/17/2016 1:21:34 PM” (2认同)
  • 如果将“ undefined”作为第一个区域设置参数感到任意,则可以根据MDN docs https://developer.mozilla.org/zh-CN/docs/传递值“ default”来利用浏览器的区域设置。 Web / JavaScript /参考/ Global_Objects / Date / toLocaleDateString#Parameters (2认同)
  • 这是对以下链接的长期挖掘,但我发现它们隐藏在哪里@MosesSchwartz:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat (2认同)
  • 请注意文档中的以下信息“要使用浏览器的默认区域设置,请传递一个空数组。” (对于语言环境参数)。 (2认同)
  • 这应该是公认的答案,它是唯一一个使用最少代码且无需外部库的答案 (2认同)

Mar*_*rko 1129

注意:下面有更好的答案.这个答案写于2010年,从那时起就有了更新更好的解决方案.OP应接受另一个答案.

function formatDate(date) {
  var monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
  ];

  var day = date.getDate();
  var monthIndex = date.getMonth();
  var year = date.getFullYear();

  return day + ' ' + monthNames[monthIndex] + ' ' + year;
}

console.log(formatDate(new Date()));  // show current date-time in console
Run Code Online (Sandbox Code Playgroud)

您可以编辑阵列monthNames以使用Jan,Feb,Mar等.

  • [moment.js](http://momentjs.com)2.9.0是**11.6k**gzipped,这个例子是**211字节**gzipped. (571认同)
  • 真的考虑使用像Moment.js或Date.js这样的库.这个问题已经解决了很多次. (341认同)
  • 为什么它们不包含`Date`对象中的函数来执行此操作? (214认同)
  • 一个重要的一点是getMonth()方法返回一个基于0的月份索引,所以例如1月将返回0 2月将返回1,等等... (62认同)
  • 我知道“ye”是年,“mo”是月,“da”是日。什么是“o”?什么是“a”?什么是“m”?您能使用正确的变量名称吗? (31认同)
  • 应该注意的是,您永远不应该使用document.write().巨大的安全性和性能问题. (26认同)
  • 你知道,因为它有很多语言环境数据,所以时刻很臃肿.您可以轻松删除它以降低文件大小.无论如何,mrzmyr将完全功能的日期解析库与示例进行了微弱的比较.没有比较imho. (8认同)
  • @TomášZato您声称答案很糟糕,但您还没有发布解释性评论,为什么,是否有原因? (6认同)
  • @BenMcIntyre但它至少会被加载和执行,也可能被解析为一些目标代码.执行4000 LOC与15有差异 (5认同)
  • 我可以在没有库的两行中获取您请求的格式:var d = new Date(); var date = d.toString().replace(/\S +\s(\ S +)\ s(\ d +)\ s(\ d +)\ s.*/,'$ 2- $ 1- $ 3'); (4认同)
  • 错误的答案是因为:a)问题的错误解决方案,产生'2010年8月10日'而非期望的'2010年8月10日'b)重新发明轮子,因为其他评论者建议momentjs是一个不错的选择,c)不考虑对于语言环境,使其在国际化应用程序中无用 (3认同)
  • 恕我直言,这是最好的答案(最后一个片段),因为允许任何格式的灵活性,即您不需要寻找满足您需求的国家/地区代码 (3认同)
  • 或者扩展 `Date` 对象,就像我在 http://stackoverflow.com/questions/3187790/convert-unix-time-to-mm-dd-yy-hhmm-24-hour-in-javascript/3189792# 所做的那样3189792 (2认同)
  • 只是注意`date.getMonth()`返回`0-11`,所以如果你打算直接使用那个数字,你想要添加`1`. (2认同)
  • @JDSmith - 它要求*Date.prototype.toString*的输出在各实现之间保持一致,但实际上并非如此. (2认同)
  • 答案是正确的,但是变量名称上的惰性确实是另一个层面。他写“da”而不是“day”。正确的变量名称真的很棒! (2认同)

Rob*_*itt 591

使用date.format库:

var dateFormat = require('dateformat');
var now = new Date();
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
Run Code Online (Sandbox Code Playgroud)

收益:

Saturday, June 9th, 2007, 5:46:21 PM 
Run Code Online (Sandbox Code Playgroud)

在npm上的dateformat

http://jsfiddle.net/phZr7/1/

  • 上述插件有14个未解决的问题.即使我找到了一个:( (16认同)
  • OP要求JS解决方案 (13认同)
  • 此解决方案也可作为npm包提供:https://www.npmjs.com/package/dateformat (5认同)
  • 我得到`要求没有定义' (5认同)
  • 这似乎是更长的解决方案,但压缩和使用日期相当的网站将是更好的解决方案! (4认同)
  • 如果您遇到导入外部依赖项的麻烦,我建议使用moment.js.它可以执行这种类型的日期格式化:https://momentjs.com/docs/#/displaying/它具有更多功能. (2认同)

seb*_*n.i 468

如果你需要使用普通的JavaScript,使用快速格式化你的日期getDate,getMonth + 1,getFullYear,getHoursgetMinutes:

var d = new Date();

var datestring = d.getDate()  + "-" + (d.getMonth()+1) + "-" + d.getFullYear() + " " +
d.getHours() + ":" + d.getMinutes();

// 16-5-2015 9:50
Run Code Online (Sandbox Code Playgroud)

或者,如果您需要用零填充:

var datestring = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" +
    d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);

// 16-05-2015 09:50
Run Code Online (Sandbox Code Playgroud)

  • 前缀"0".slice(-2)是确保填充零的非常好的方法.Melikes (51认同)
  • 您还可以使用.toString()。padStart(2,'0')填充零 (6认同)
  • @BennyJobigan应该指出,`String.padStart()`仅可用于ECMAScript 2017。 (2认同)

sim*_*imo 387

好吧,我想要的是将今天的日期转换为MySQL友好的日期字符串,如2012-06-23,并在我的一个查询中使用该字符串作为参数.我发现的简单解决方案是这样的:

var today = new Date().toISOString().slice(0, 10);
Run Code Online (Sandbox Code Playgroud)

请注意,上述解决方案考虑您的时区偏移.

您可以考虑使用此功能:

function toJSONLocal (date) {
    var local = new Date(date);
    local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
    return local.toJSON().slice(0, 10);
}
Run Code Online (Sandbox Code Playgroud)

如果您在当天的开始/结束时执行此代码,这将为您提供正确的日期.

  • Y10K兼容版本:`var today = new Date().toISOString().slice(0,-14)`:) (20认同)
  • 或者像这个`new Date().toISOString().split('T')[0]` (17认同)
  • 你可以用`new Date(date +"UTC")`来欺骗时区,你可以消除setMinutes线.伙计,javascript很脏 (8认同)
  • 只是评论缺乏时区并不是“一天开始/结束时”的一些小不便。例如,在澳大利亚,日期可能会错误到上午 11 点左右——将近半天! (4认同)
  • `new Date()。toISOString()。slice(0,16).replace('T','')`以包含时间 (3认同)

Adr*_*ire 197

自定义格式功能:

对于固定格式,一个简单的功能可以完成工作.以下示例生成国际格式YYYY-MM-DD:

function dateToYMD(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1; //Month from 0 to 11
    var y = date.getFullYear();
    return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}

console.log(dateToYMD(new Date(2017,10,5))); // Nov 5
Run Code Online (Sandbox Code Playgroud)

OP格式可以生成如下:

function dateToYMD(date) {
    var strArray=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var d = date.getDate();
    var m = strArray[date.getMonth()];
    var y = date.getFullYear();
    return '' + (d <= 9 ? '0' + d : d) + '-' + m + '-' + y;
}
console.log(dateToYMD(new Date(2017,10,5))); // Nov 5
Run Code Online (Sandbox Code Playgroud)

注意:然而,扩展JavaScript标准库通常不是一个好主意(例如,通过将此函数添加到Date的原型).

更高级的功能可以基于格式参数生成可配置输出.

如果要编写格式化函数太长,那么就会有很多库.其他一些答案已经列举了它们.但是,越来越多的依赖关系也会与之相反.

标准ECMAScript格式化功能:

由于ECMAScript的更新版本,Date该类具有一些特定的格式化函数:

toDateString:依赖于实现,仅显示日期.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.todatestring

new Date().toDateString(); // e.g. "Fri Nov 11 2016"
Run Code Online (Sandbox Code Playgroud)

toISOString:显示ISO 8601日期和时间.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.toisostring

new Date().toISOString(); // e.g. "2016-11-21T08:00:00.000Z"
Run Code Online (Sandbox Code Playgroud)

toJSON:JSON的Stringifier.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tojson

new Date().toJSON(); // e.g. "2016-11-21T08:00:00.000Z"
Run Code Online (Sandbox Code Playgroud)

toLocaleDateString:依赖于实现,以区域设置格式的日期.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocaledatestring

new Date().toLocaleDateString(); // e.g. "21/11/2016"
Run Code Online (Sandbox Code Playgroud)

toLocaleString:依赖于实现,以区域设置格式的日期和时间.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocalestring

new Date().toLocaleString(); // e.g. "21/11/2016, 08:00:00 AM"
Run Code Online (Sandbox Code Playgroud)

toLocaleTimeString:依赖于实现,是区域设置格式的时间.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocaletimestring

new Date().toLocaleTimeString(); // e.g. "08:00:00 AM"
Run Code Online (Sandbox Code Playgroud)

toString:Date的通用toString.

http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tostring

new Date().toString(); // e.g. "Fri Nov 21 2016 08:00:00 GMT+0100 (W. Europe Standard Time)"
Run Code Online (Sandbox Code Playgroud)

注意:可以从那些格式>生成自定义输出

new Date().toISOString().slice(0,10); //return YYYY-MM-DD
Run Code Online (Sandbox Code Playgroud)

示例摘要:

console.log("1) "+  new Date().toDateString());
console.log("2) "+  new Date().toISOString());
console.log("3) "+  new Date().toJSON());
console.log("4) "+  new Date().toLocaleDateString());
console.log("5) "+  new Date().toLocaleString());
console.log("6) "+  new Date().toLocaleTimeString());
console.log("7) "+  new Date().toString());
console.log("8) "+  new Date().toISOString().slice(0,10));
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的最后一个。.对于设置HTML日期输入的日期值很有用。 (3认同)

Dmi*_*lov 172

如果您已经在项目中使用jQuery UI,则可以这样做:

var formatted = $.datepicker.formatDate("M d, yy", new Date("2014-07-08T09:02:21.377"));

// formatted will be 'Jul 8, 2014'
Run Code Online (Sandbox Code Playgroud)

此处提供了一些可供使用的日期选择器日期格式选项.

  • 正如我所说 - 如果已经在项目中使用了jQueryUI - 为什么不重新使用datepicker日期格式化功能?嘿伙计们,我不会理解为什么我会对我的答案进行否定投票?请解释. (13认同)
  • 我认为不可能完全避免某人因错误或缺乏意识而做出的所有奇怪决定. (12认同)
  • 这可能是因为有人可能只为日期格式函数包含jQuery UI,或者可能是因为datepicker是库的可选部分,但可能是因为讨厌jQuery很时髦. (7认同)
  • @sennett:讨厌jQuery很时尚?所以,你的裤子走到腿的一半,我想...这就是在没有jQuery的情况下尝试编码的原因就像大多数JavaScript的历史一样...... (7认同)
  • 无论如何,这是一个有用且完全合理的答案 - 再次,70%的网站使用jQuery.由于开发者的宗教信仰,它不应该被低估. (5认同)

小智 128

我想你可以使用非标准的 Date方法toLocaleFormat(formatString)

formatString:strftime() C中函数所需格式的格式字符串.

var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011
Run Code Online (Sandbox Code Playgroud)

参考文献:

  • toLocaleFormat()似乎只适用于Firefox.IE和Chrome都失败了. (154认同)
  • Chrome有.toLocaleString('en')方法.因为看起来新的浏览器支持这个https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString (16认同)
  • 请在此处阅读警告:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleFormat (8认同)
  • 如果每个人都可以实现它,这将是最好的解决方案.该死的你/铬 (6认同)
  • @santa:的确如此.也许有一个公平的理由不遵循Mozilla的主导,但事实上即使ES6没有标准功能,这表明它仍然是黑客的语言,而不是开发人员的语言. (5认同)
  • `new Intl.DateTimeFormat` 似乎是替代品 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat (2认同)
  • 7 年后,此功能在其他浏览器中仍然不起作用,并在 Firefox 中被弃用 [Deprecated_toLocaleFormat](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Fehler/Deprecated_toLocaleFormat) (2认同)
  • 自 2021 年 12 月起已弃用 (2认同)

Mit*_*ski 99

简单的JavaScript是小型onetimers的最佳选择.

另一方面,如果您需要更多日期,MomentJS是一个很好的解决方案.

例如:

moment().format('YYYY-MM-DD HH:m:s');     // now() -> 2015-03-24 14:32:20
moment("20111031", "YYYYMMDD").fromNow(); // 3 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow();        // 11 hours ago
moment().endOf('day').fromNow();          // in 13 hours
Run Code Online (Sandbox Code Playgroud)

  • 片刻已过时,请使用luxon (2认同)
  • 值得一提的是:不要使用“YYYY”,除非您知道“YYYY”和“yyyy”之间的区别:/sf/ask/1059348461/ Between-yyyy-and-yyyy-in-nsdateformatter (2认同)
  • @Domin 是 iOS 中 NSDateFormatter 特有的,例如 Objective-C 或 Swift 中使用的。这个问题是关于浏览器中的 Javascript,这个答案使用 MomentJS,其中“YYYY”(不是“yyyy”)是标准年份,“GGGG”(不是“YYYY”)是 ISO 基于周的年份。 (2认同)

Joh*_*ers 94

在现代浏览器(*)中,您可以这样做:

var today = new Date().toLocaleDateString('en-GB', {
    day : 'numeric',
    month : 'short',
    year : 'numeric'
}).split(' ').join('-');
Run Code Online (Sandbox Code Playgroud)

如果今天执行输出(2016年1月24日):

'24-Jan-2016'
Run Code Online (Sandbox Code Playgroud)

(*) 根据MDN,"现代浏览器"意味着Chrome 24 +,Firefox 29 +,Internet Explorer 11,Edge 12 +,Opera 15+和Safari 夜间构建.


NiK*_*iKo 52

你应该看看date.js.它添加了许多方便的帮助程序来处理日期,例如,在您的情况下:

var date = Date.parse('2010-08-10');
console.log(date.toString('dd-MMM-yyyy'));
Run Code Online (Sandbox Code Playgroud)

入门:http://www.datejs.com/2007/11/27/getting-started-with-datejs/


use*_*584 35

@Sébastien - 替代所有浏览器支持

new Date(parseInt(496407600)*1000).toLocaleDateString('de-DE', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).replace(/\./g, '/');
Run Code Online (Sandbox Code Playgroud)

文档:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

  • 您可以简单地使用'en-GB'作为区域设置,而不是使用.replace().:) (5认同)

JD *_*ith 34

我可以在一行中使用没有库和没有Date方法获得您请求的格式,只是正则表达式:

var d = (new Date()).toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/,'$2-$1-$3');
// date will be formatted as "14-Oct-2015" (pass any date object in place of 'new Date()')
Run Code Online (Sandbox Code Playgroud)

更新:正如@RobG所指出的,Date.prototype.toString()的输出是依赖于实现的.因此,如果您使用此解决方案,请谨慎使用并在必要时进行修改.在我的测试中,这在北美可靠地运行,主要浏览器(Chrome,Safari,Firefox和IE)都返回相同的字符串格式.


vde*_*nne 29

使用ECMAScript Edition 6(ES6/ES2015)字符串模板:

let d = new Date();
let formatted = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
Run Code Online (Sandbox Code Playgroud)

如果您需要更改分隔符:

const delimiter = '/';
let formatted = [d.getFullYear(), d.getMonth() + 1, d.getDate()].join(delimiter);
Run Code Online (Sandbox Code Playgroud)


Ali*_*eza 26

好的,我们有一个名为Intl的东西,这对于在JavaScript中格式化日期非常有用:

您的日期如下:

var date = '10/8/2010';
Run Code Online (Sandbox Code Playgroud)

然后使用新的Date()更改为Date,如下所示:

date = new Date(date);
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用以下语言环境列表以任何方式格式化它:

date = new Intl.DateTimeFormat('en-AU').format(date); // Australian date format: "8/10/2010" 
Run Code Online (Sandbox Code Playgroud)


date = new Intl.DateTimeFormat('en-US').format(date); // USA date format: "10/8/2010" 
Run Code Online (Sandbox Code Playgroud)


date = new Intl.DateTimeFormat('ar-EG').format(date);  // Arabic date format: "??/???/????"
Run Code Online (Sandbox Code Playgroud)

如果您确实需要上面提到的格式,您可以:

date = new Date(Date.UTC(2010, 7, 10, 0, 0, 0));
var options = {year: "numeric", month: "short", day: "numeric"};
date = new Intl.DateTimeFormat("en-AU", options).format(date).replace(/\s/g, '-');
Run Code Online (Sandbox Code Playgroud)

结果将是:

"10-Aug-2010"
Run Code Online (Sandbox Code Playgroud)

有关ECMAScript Internationalization API(Intl)的更多详细信息,请访问此处.


lew*_*dev 24

打包解决方案: moment.js

如果你想使用一个解决方案来适应所有,我强烈建议使用moment.js,它也可以在许多语言环境/语言和大量其他功能中进行格式化.

安装:

npm install luxonyarn add luxon(访问其他安装方法的链接)

例:

luxon.DateTime.fromISO('2010-08-10').toFormat('yyyy-LLL-dd');

产量:

10 - 8 - 2010

手动解决方案

使用与Moment.js,Class DateTimeFormatter(Java)Class SimpleDateFormat(Java)类似的格式,我实现了一个全面的解决方案formatDate(date, patternStr),其中代码易于阅读和修改.您可以显示日期,时间,上午/下午等.有关更多示例,请参阅代码.

例:

formatDate(new Date(), 'EEEE, MMMM d, yyyy HH:mm:ss:S')

(formatDate在下面的代码片段中实现)

产量:

2018年10月12日星期五18:11:23:445

点击"运行代码段"即可试用该代码.

日期和时间模式

yy= 2位数年份; yyyy=全年

M=数字月; MM= 2位数月份; MMM=短月名; MMMM=完整的月份名称

EEEE=完整的工作日名称; EEE=工作日的简短名称

d=数字日; dd= 2位数日

h=上午/下午; hh=上午2点/下午; H=小时; HH= 2位数小时

m=分钟; mm= 2位数分钟; aaa=上午/下午

s=秒; ss= 2位数秒

S =毫秒

var monthNames = [
  "January", "February", "March", "April", "May", "June", "July",
  "August", "September", "October", "November", "December"
];
var dayOfWeekNames = [
  "Sunday", "Monday", "Tuesday",
  "Wednesday", "Thursday", "Friday", "Saturday"
];
function formatDate(date, patternStr){
    if (!patternStr) {
        patternStr = 'M/d/yyyy';
    }
    var day = date.getDate(),
        month = date.getMonth(),
        year = date.getFullYear(),
        hour = date.getHours(),
        minute = date.getMinutes(),
        second = date.getSeconds(),
        miliseconds = date.getMilliseconds(),
        h = hour % 12,
        hh = twoDigitPad(h),
        HH = twoDigitPad(hour),
        mm = twoDigitPad(minute),
        ss = twoDigitPad(second),
        aaa = hour < 12 ? 'AM' : 'PM',
        EEEE = dayOfWeekNames[date.getDay()],
        EEE = EEEE.substr(0, 3),
        dd = twoDigitPad(day),
        M = month + 1,
        MM = twoDigitPad(M),
        MMMM = monthNames[month],
        MMM = MMMM.substr(0, 3),
        yyyy = year + "",
        yy = yyyy.substr(2, 2)
    ;
    // checks to see if month name will be used
    patternStr = patternStr
      .replace('hh', hh).replace('h', h)
      .replace('HH', HH).replace('H', hour)
      .replace('mm', mm).replace('m', minute)
      .replace('ss', ss).replace('s', second)
      .replace('S', miliseconds)
      .replace('dd', dd).replace('d', day)
      
      .replace('EEEE', EEEE).replace('EEE', EEE)
      .replace('yyyy', yyyy)
      .replace('yy', yy)
      .replace('aaa', aaa);
    if (patternStr.indexOf('MMM') > -1) {
        patternStr = patternStr
          .replace('MMMM', MMMM)
          .replace('MMM', MMM);
    }
    else {
        patternStr = patternStr
          .replace('MM', MM)
          .replace('M', M);
    }
    return patternStr;
}
function twoDigitPad(num) {
    return num < 10 ? "0" + num : num;
}
console.log(formatDate(new Date()));
console.log(formatDate(new Date(), 'dd-MMM-yyyy')); //OP's request
console.log(formatDate(new Date(), 'EEEE, MMMM d, yyyy HH:mm:ss.S aaa'));
console.log(formatDate(new Date(), 'EEE, MMM d, yyyy HH:mm'));
console.log(formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss.S'));
console.log(formatDate(new Date(), 'M/dd/yyyy h:mmaaa'));
Run Code Online (Sandbox Code Playgroud)

  • 片刻已过时,请使用luxon (2认同)

jmi*_*lia 18

这是我刚刚编写的一些代码,用于处理我正在处理的项目的日期格式.它模仿PHP日期格式化功能以满足我的需求.随意使用它,它只是扩展已存在的Date()对象.这可能不是最优雅的解决方案,但它可以满足我的需求.

var d = new Date(); 
d_string = d.format("m/d/Y h:i:s");

/**************************************
 * Date class extension
 * 
 */
    // Provide month names
    Date.prototype.getMonthName = function(){
        var month_names = [
                            'January',
                            'February',
                            'March',
                            'April',
                            'May',
                            'June',
                            'July',
                            'August',
                            'September',
                            'October',
                            'November',
                            'December'
                        ];

        return month_names[this.getMonth()];
    }

    // Provide month abbreviation
    Date.prototype.getMonthAbbr = function(){
        var month_abbrs = [
                            'Jan',
                            'Feb',
                            'Mar',
                            'Apr',
                            'May',
                            'Jun',
                            'Jul',
                            'Aug',
                            'Sep',
                            'Oct',
                            'Nov',
                            'Dec'
                        ];

        return month_abbrs[this.getMonth()];
    }

    // Provide full day of week name
    Date.prototype.getDayFull = function(){
        var days_full = [
                            'Sunday',
                            'Monday',
                            'Tuesday',
                            'Wednesday',
                            'Thursday',
                            'Friday',
                            'Saturday'
                        ];
        return days_full[this.getDay()];
    };

    // Provide full day of week name
    Date.prototype.getDayAbbr = function(){
        var days_abbr = [
                            'Sun',
                            'Mon',
                            'Tue',
                            'Wed',
                            'Thur',
                            'Fri',
                            'Sat'
                        ];
        return days_abbr[this.getDay()];
    };

    // Provide the day of year 1-365
    Date.prototype.getDayOfYear = function() {
        var onejan = new Date(this.getFullYear(),0,1);
        return Math.ceil((this - onejan) / 86400000);
    };

    // Provide the day suffix (st,nd,rd,th)
    Date.prototype.getDaySuffix = function() {
        var d = this.getDate();
        var sfx = ["th","st","nd","rd"];
        var val = d%100;

        return (sfx[(val-20)%10] || sfx[val] || sfx[0]);
    };

    // Provide Week of Year
    Date.prototype.getWeekOfYear = function() {
        var onejan = new Date(this.getFullYear(),0,1);
        return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
    } 

    // Provide if it is a leap year or not
    Date.prototype.isLeapYear = function(){
        var yr = this.getFullYear();

        if ((parseInt(yr)%4) == 0){
            if (parseInt(yr)%100 == 0){
                if (parseInt(yr)%400 != 0){
                    return false;
                }
                if (parseInt(yr)%400 == 0){
                    return true;
                }
            }
            if (parseInt(yr)%100 != 0){
                return true;
            }
        }
        if ((parseInt(yr)%4) != 0){
            return false;
        } 
    };

    // Provide Number of Days in a given month
    Date.prototype.getMonthDayCount = function() {
        var month_day_counts = [
                                    31,
                                    this.isLeapYear() ? 29 : 28,
                                    31,
                                    30,
                                    31,
                                    30,
                                    31,
                                    31,
                                    30,
                                    31,
                                    30,
                                    31
                                ];

        return month_day_counts[this.getMonth()];
    } 

    // format provided date into this.format format
    Date.prototype.format = function(dateFormat){
        // break apart format string into array of characters
        dateFormat = dateFormat.split("");

        var date = this.getDate(),
            month = this.getMonth(),
            hours = this.getHours(),
            minutes = this.getMinutes(),
            seconds = this.getSeconds();
        // get all date properties ( based on PHP date object functionality )
        var date_props = {
            d: date < 10 ? '0'+date : date,
            D: this.getDayAbbr(),
            j: this.getDate(),
            l: this.getDayFull(),
            S: this.getDaySuffix(),
            w: this.getDay(),
            z: this.getDayOfYear(),
            W: this.getWeekOfYear(),
            F: this.getMonthName(),
            m: month < 10 ? '0'+(month+1) : month+1,
            M: this.getMonthAbbr(),
            n: month+1,
            t: this.getMonthDayCount(),
            L: this.isLeapYear() ? '1' : '0',
            Y: this.getFullYear(),
            y: this.getFullYear()+''.substring(2,4),
            a: hours > 12 ? 'pm' : 'am',
            A: hours > 12 ? 'PM' : 'AM',
            g: hours % 12 > 0 ? hours % 12 : 12,
            G: hours > 0 ? hours : "12",
            h: hours % 12 > 0 ? hours % 12 : 12,
            H: hours,
            i: minutes < 10 ? '0' + minutes : minutes,
            s: seconds < 10 ? '0' + seconds : seconds           
        };

        // loop through format array of characters and add matching data else add the format character (:,/, etc.)
        var date_string = "";
        for(var i=0;i<dateFormat.length;i++){
            var f = dateFormat[i];
            if(f.match(/[a-zA-Z]/g)){
                date_string += date_props[f] ? date_props[f] : '';
            } else {
                date_string += f;
            }
        }

        return date_string;
    };
/*
 *
 * END - Date class extension
 * 
 ************************************/
Run Code Online (Sandbox Code Playgroud)


tod*_*dmo 16

TypeScript 版本

它可以轻松增强以支持任何所需的格式字符串。当像这样的通用解决方案很容易创建,并且日期格式在应用程序中经常出现时,我不建议在整个应用程序中硬编码日期格式代码。它更难阅读并且隐藏你的意图。格式字符串清楚地表明您的意图。

原型函数

interface Date {
    format(formatString: string): string;
}

Date.prototype.format = function (formatString: string): string {
  return Object.entries({
    YYYY: this.getFullYear(),
    YY: this.getFullYear().toString().substring(2),
    yyyy: this.getFullYear(),
    yy: this.getFullYear().toString().substring(2),
    MMMM: this.toLocaleString('default', { month: 'long' }),
    MMM: this.toLocaleString('default', { month: 'short' }),
    MM: (this.getMonth() + 1).toString().padStart(2, '0'),
    M: this.getMonth() + 1,
    DDDD: this.toLocaleDateString('default', { weekday: 'long' }),
    DDD: this.toLocaleDateString('default', { weekday: 'short' }),
    DD: this.getDate().toString().padStart(2, '0'),
    D: this.getDate(),
    dddd: this.toLocaleDateString('default', { weekday: 'long' }),
    ddd: this.toLocaleDateString('default', { weekday: 'short' }),
    dd: this.getDate().toString().padStart(2, '0'),
    d: this.getDate(),
    HH: this.getHours().toString().padStart(2, '0'), // military
    H: this.getHours().toString(), // military
    hh: (this.getHours() % 12).toString().padStart(2, '0'),
    h: (this.getHours() % 12).toString(),
    mm: this.getMinutes().toString().padStart(2, '0'),
    m: this.getMinutes(),
    SS: this.getSeconds().toString().padStart(2, '0'),
    S: this.getSeconds(),
    ss: this.getSeconds().toString().padStart(2, '0'),
    s: this.getSeconds(),
    TTT: this.getMilliseconds().toString().padStart(3, '0'),
    ttt: this.getMilliseconds().toString().padStart(3, '0'),
    AMPM: this.getHours() < 13 ? 'AM' : 'PM',
    ampm: this.getHours() < 13 ? 'am' : 'pm',
  }).reduce((acc, entry) => {
    return acc.replace(entry[0], entry[1].toString())
  }, formatString)
}
Run Code Online (Sandbox Code Playgroud)

演示

function unitTest() {
    var d: Date = new Date()
    console.log(d.format('MM/dd/yyyy hh:mm:ss')) // 12/14/2022 03:38:31
    console.log(d.format('yyyy-MM-dd HH:mm:ss')) // 2022-12-14 15:38:31
}

unitTest()
Run Code Online (Sandbox Code Playgroud)

JavaScript 版本

一样的。只需删除接口以及冒号后面的类型名称及其关联的冒号即可。

片段

interface Date {
    format(formatString: string): string;
}

Date.prototype.format = function (formatString: string): string {
  return Object.entries({
    YYYY: this.getFullYear(),
    YY: this.getFullYear().toString().substring(2),
    yyyy: this.getFullYear(),
    yy: this.getFullYear().toString().substring(2),
    MMMM: this.toLocaleString('default', { month: 'long' }),
    MMM: this.toLocaleString('default', { month: 'short' }),
    MM: (this.getMonth() + 1).toString().padStart(2, '0'),
    M: this.getMonth() + 1,
    DDDD: this.toLocaleDateString('default', { weekday: 'long' }),
    DDD: this.toLocaleDateString('default', { weekday: 'short' }),
    DD: this.getDate().toString().padStart(2, '0'),
    D: this.getDate(),
    dddd: this.toLocaleDateString('default', { weekday: 'long' }),
    ddd: this.toLocaleDateString('default', { weekday: 'short' }),
    dd: this.getDate().toString().padStart(2, '0'),
    d: this.getDate(),
    HH: this.getHours().toString().padStart(2, '0'), // military
    H: this.getHours().toString(), // military
    hh: (this.getHours() % 12).toString().padStart(2, '0'),
    h: (this.getHours() % 12).toString(),
    mm: this.getMinutes().toString().padStart(2, '0'),
    m: this.getMinutes(),
    SS: this.getSeconds().toString().padStart(2, '0'),
    S: this.getSeconds(),
    ss: this.getSeconds().toString().padStart(2, '0'),
    s: this.getSeconds(),
    TTT: this.getMilliseconds().toString().padStart(3, '0'),
    ttt: this.getMilliseconds().toString().padStart(3, '0'),
    AMPM: this.getHours() < 13 ? 'AM' : 'PM',
    ampm: this.getHours() < 13 ? 'am' : 'pm',
  }).reduce((acc, entry) => {
    return acc.replace(entry[0], entry[1].toString())
  }, formatString)
}
Run Code Online (Sandbox Code Playgroud)

  • @Willian,[此时此刻](https://medium.com/rise-engineering/how-we-management-to-shed-300kb-of-moment-js-size-in-angular -d2931d448194)。如果我不向你指出那一刻已经过去了,那我就太不友善了。因此,找到另一个不会消失的较小的库,它支持模块化导入。[github](https://github.com/moment/moment) 自述文件指出它是遗留的,您应该选择另一个库。你的研究落后了。因此,在您找到最佳替代品后,请再次向我提出更强有力的库与您自己的库的案例。 (4认同)
  • JavaScript 中没有“格式” (3认同)

Pra*_*DLV 15

不使用任何外部库的JavaScript解决方案:

var now = new Date()
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
var formattedDate = now.getDate() + "-" + months[now.getMonth()] + "-" + now.getFullYear()
alert(formattedDate)
Run Code Online (Sandbox Code Playgroud)


web*_*bzy 15

如果您在代码中使用jQuery UI,则会调用一个内置函数formatDate().我这样使用它来格式化今天的日期:

var testdate = Date();
testdate = $.datepicker.formatDate( "d-M-yy",new Date(testdate));
alert(testdate);
Run Code Online (Sandbox Code Playgroud)

您可以在jQuery UI文档中看到 许多其他格式化日期示例.


Vij*_*iya 15

我们有很多解决方案,但我认为其中最好的是Moment.js.所以我个人建议使用Moment.js进行日期和时间操作.

console.log(moment().format('DD-MMM-YYYY'));
Run Code Online (Sandbox Code Playgroud)
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
Run Code Online (Sandbox Code Playgroud)


Ima*_*our 15

在JavaScript中格式化DateTimes的一种有用且灵活的方法是Intl.DateTimeFormat:

var date = new Date();
var options = { year: 'numeric', month: 'short', day: '2-digit'};
var _resultDate = new Intl.DateTimeFormat('en-GB', options).format(date);
// The _resultDate is: "12 Oct 2017"
// Replace all spaces with - and then log it.
console.log(_resultDate.replace(/ /g,'-'));
Run Code Online (Sandbox Code Playgroud)

结果是: "12-Oct-2017"

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

Intl.DateTimeFormat对象是对象的构造函数,用于启用语言敏感的日期和时间格式.

句法

new Intl.DateTimeFormat([locales[, options]])
Intl.DateTimeFormat.call(this[, locales[, options]])
Run Code Online (Sandbox Code Playgroud)

参数

语言环境

可选的.带有BCP 47语言标记的字符串,或此类字符串的数组.有关locales参数的一般形式和解释,请参阅Intl页面.允许使用以下Unicode扩展密钥:

nu
Numbering system. Possible values include: "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt".
ca
Calendar. Possible values include: "buddhist", "chinese", "coptic", "ethioaa", "ethiopic", "gregory", "hebrew", "indian", "islamic", "islamicc", "iso8601", "japanese", "persian", "roc".
Run Code Online (Sandbox Code Playgroud)

选项

可选的.具有以下部分或全部属性的对象:

localeMatcher

要使用的区域设置匹配算法.可能的值是"lookup""best fit"; 默认是"best fit".有关此选项的信息,请参阅Intl页面.

时区

要使用的时区.实现必须识别的唯一值是"UTC"; 默认值是运行时的默认时区.实现也可以识别IANA时区数据库的时区名称,例如"Asia/Shanghai","Asia/Kolkata","America/New_York".

hour12

是否使用12小时时间(而不是24小时时间).可能的值是truefalse; 默认值取决于语言环境.

formatMatcher

要使用的格式匹配算法.可能的值是"basic""best fit"; 默认是"best fit".有关使用此属性的信息,请参阅以下段落.

以下属性描述了在格式化输出中使用的日期时间组件及其所需的表示形式.需要实现至少支持以下子集:

weekday, year, month, day, hour, minute, second
weekday, year, month, day
year, month, day
year, month
month, day
hour, minute, second
hour, minute
Run Code Online (Sandbox Code Playgroud)

实现可以支持其他子集,并且将针对所有可用的子集表示组合协商请求以找到最佳匹配.有两种算法可用于此协商,并由formatMatcher属性选择:完全指定的"basic"算法和依赖于实现的"最佳拟合"算法.

平日

工作日的代表.可能的值是"narrow","short","long".

时代

时代的代表.可能的值是"narrow","short","long".

年度代表.可能的值是"numeric","2-digit".

本月的代表.可能的值是"numeric","2-digit","narrow","short","long".

当天的代表.可能的值是"numeric","2-digit".

小时

小时的表示.可能的值是"numeric","2-digit".

分钟

分钟的表示.可能的值是"numeric","2-digit".

第二

第二个的表示.可能的值是"numeric","2-digit".

TIMEZONENAME

时区名称的表示形式.可能的值是"short","long".每个日期时间组件属性的默认值是未定义的,但如果未定义所有组件属性,则假定年,月和日"numeric".

在线查看

更多细节


Mr *_*uga 14

嗨检查这是否有助于解决您的问题.

var d = new Date();

var options = {   
    day: 'numeric',
    month: 'long', 
    year: 'numeric'
};

console.log(d.toLocaleDateString('en-ZA', options));
Run Code Online (Sandbox Code Playgroud)

找到格式的日期

  • 或`d.toLocaleDateString('en-US',options);`(如果您在美国)。 (2认同)

Kir*_*eck 14

new Date().toLocaleDateString()

// "3/21/2018"
Run Code Online (Sandbox Code Playgroud)

developer.mozilla.org上有更多文档


Mel*_*hia 14

你应该看看DayJs 它是对 momentJs 的重制,但面向模块化架构的更轻。

具有相同现代 API 的 Moment.js 的快速 2kB 替代品

Day.js 是一个极简的 JavaScript 库,它使用与 Moment.js 兼容的 API 为现代浏览器解析、验证、操作和显示日期和时间。如果您使用 Moment.js,您就已经知道如何使用 Day.js。

var date = Date.now();
const formatedDate = dayjs(date).format("YYYY-MM-DD")
console.log(formatedDate);
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.16/dayjs.min.js" crossorigin="anonymous"></script>
Run Code Online (Sandbox Code Playgroud)


Ami*_*pta 13

这就是我为我的npm插件实现的方式

var monthNames = [
  "January", "February", "March",
  "April", "May", "June", "July",
  "August", "September", "October",
  "November", "December"
];

var Days = [
  "Sunday", "Monday", "Tuesday", "Wednesday",
  "Thursday", "Friday", "Saturday"
];

var formatDate = function(dt,format){
  format = format.replace('ss', pad(dt.getSeconds(),2));
  format = format.replace('s', dt.getSeconds());
  format = format.replace('dd', pad(dt.getDate(),2));
  format = format.replace('d', dt.getDate());
  format = format.replace('mm', pad(dt.getMinutes(),2));
  format = format.replace('m', dt.getMinutes());
  format = format.replace('MMMM', monthNames[dt.getMonth()]);
  format = format.replace('MMM', monthNames[dt.getMonth()].substring(0,3));
  format = format.replace('MM', pad(dt.getMonth()+1,2));
  format = format.replace(/M(?![ao])/, dt.getMonth()+1);
  format = format.replace('DD', Days[dt.getDay()]);
  format = format.replace(/D(?!e)/, Days[dt.getDay()].substring(0,3));
  format = format.replace('yyyy', dt.getFullYear());
  format = format.replace('YYYY', dt.getFullYear());
  format = format.replace('yy', (dt.getFullYear()+"").substring(2));
  format = format.replace('YY', (dt.getFullYear()+"").substring(2));
  format = format.replace('HH', pad(dt.getHours(),2));
  format = format.replace('H', dt.getHours());
  return format;
}

pad = function(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
Run Code Online (Sandbox Code Playgroud)


ppi*_*com 13

Date构造(和Date.parse())仅构建日期时接受一个格式作为一个参数,那就是ISO 8601

// new Date('YYYY-MM-DDTHH:mm:ss.sssZ')
const date = new Date('2017-08-15')
Run Code Online (Sandbox Code Playgroud)

但是由于浏览器的差异和不一致,强烈建议不要从字符串解析 a(MDN 建议不要使用日期字符串创建日期)。

推荐的替代方法是直接从数字数据构建您的 Date 实例,如下所示:

new Date(2017, 7, 15) // month is zero-indexed
Run Code Online (Sandbox Code Playgroud)

那就是解析。现在,要将您的日期格式化为您想要的字符串,您有几个 Date 对象本机的选项(尽管我相信没有一个选项符合您需要的格式):

date.toString()       // 'Wed Jan 23 2019 17:23:42 GMT+0800 (Singapore Standard Time)'
date.toDateString()   // 'Wed Jan 23 2019'
date.toLocaleString() // '23/01/2019, 17:23:42'
date.toLocaleString() // '23/01/2019, 17:23:42'
date.toGMTString()    // 'Wed, 23 Jan 2019 09:23:42 GMT'
date.toUTCString()    // 'Wed, 23 Jan 2019 09:23:42 GMT'
date.toISOString()    // '2019-01-23T09:23:42.079Z'
Run Code Online (Sandbox Code Playgroud)

对于其他格式选项,恐怕您将不得不求助于诸如moment.jsday.js之类的库。

感谢泽尔刘氏这篇文章的日期格式设置提示


Dav*_*ave 10

受到JD Smith奇妙的正则表达式解决方案的启发,我突然有了这个令人头疼的想法:

var D = Date().toString().split(" ");
console.log(D[2] + "-" + D[1] + "-" + D[3]);
Run Code Online (Sandbox Code Playgroud)


cat*_*ith 10

简单的格式化程序:

function fmt(date, format = 'YYYY-MM-DDThh:mm:ss') {
  const pad2 = (n) => n.toString().padStart(2, '0');

  const map = {
    YYYY: date.getFullYear(),
    MM: pad2(date.getMonth() + 1),
    DD: pad2(date.getDate()),
    hh: pad2(date.getHours()),
    mm: pad2(date.getMinutes()),
    ss: pad2(date.getSeconds()),
  };

  return Object.entries(map).reduce((prev, entry) => prev.replace(...entry), format);
}

// Usage
console.log(
  fmt(new Date(), 'YYYY-MM-DDThh:mm:ss') // '2023-03-04T10:30:24'
);
console.log(
  fmt(new Date(), 'MM/DD/YYYY, hh:mm:ss') // '03/04/2023, 10:30:24'
);
Run Code Online (Sandbox Code Playgroud)


Gen*_*kin 9

var today = new Date();
var formattedToday = today.toLocaleDateString() + ' ' + today.toLocaleTimeString();
Run Code Online (Sandbox Code Playgroud)


Chr*_*zak 9

为了格式化日期例如10-Aug-2010,你可能想使用.toDateString()ES6阵列解构。

const formattedDate = new Date().toDateString()
// The above yields e.g. 'Mon Jan 06 2020'

const [, month, day, year] = formattedDate.split(' ')

const ddMmmYyyy = `${day}-${month}-${year}`
// or
const ddMmmYyyy = [day, month, year].join('-')
Run Code Online (Sandbox Code Playgroud)


has*_*sen 8

Sugar.js具有对Date对象的出色扩展,包括Date.format方法.

文档中的示例:

Date.create().format('{Weekday} {Month} {dd}, {yyyy}');

Date.create().format('{12hr}:{mm}{tt}')
Run Code Online (Sandbox Code Playgroud)


Moh*_*fei 8

JavaScriptIntl.DateTimeFormat方法提供了一种格式化日期的便捷方法。

以下是构建所需格式的方法:

const date = new Date("2010-08-10");

let d=new Intl.DateTimeFormat('en-GB',{year:"numeric", month:"short",day:"2-digit"}).format(date).split(" ").join("-");

console.log(d);
Run Code Online (Sandbox Code Playgroud)


小智 8

你可以简单地这样做:

let date = new Date().toLocaleDateString('en-us', {day: 'numeric'})
let month = new Date().toLocaleDateString('en-us', {month: 'long'})
let year = new Date().toLocaleDateString('en-us', {year: 'numeric'})
const FormattedDate = `${date}-${month}-${year}`
console.log(FormattedDate) // 26-March-2022
Run Code Online (Sandbox Code Playgroud)


Hin*_*ich 7

任何人都在寻找一个非常简单的ES6解决方案来复制,粘贴和采用:

const dateToString = d => `${d.getFullYear()}-${('00' + (d.getMonth() + 1)).slice(-2)}-${('00' + d.getDate()).slice(-2)}` 

// how to use:
const myDate = new Date(Date.parse('04 Dec 1995 00:12:00 GMT'))
console.log(dateToString(myDate)) // 1995-12-04
Run Code Online (Sandbox Code Playgroud)


Arj*_*yak 6

尝试这个:

function init(){
    var d = new Date();
    var day = d.getDate();
    var x = d.toDateString().substr(4, 3);
    var year = d.getFullYear();
    document.querySelector("#mydate").innerHTML = day + '-' + x + '-' + year;
}
window.onload = init;
Run Code Online (Sandbox Code Playgroud)
<div id="mydate"></div>
Run Code Online (Sandbox Code Playgroud)


sit*_*ite 6

要获取“ 2010年8月10日”,请尝试:

var date = new Date('2010-08-10 00:00:00');
date = date.toLocaleDateString(undefined, {day:'2-digit'}) + '-' + date.toLocaleDateString(undefined, {month:'short'}) + '-' + date.toLocaleDateString(undefined, {year:'numeric'})
Run Code Online (Sandbox Code Playgroud)

有关浏览器的支持,请参见toLocaleDateString


ami*_*309 5

DateFormatter.formatDate(new Date(2010,7,10), 'DD-MMM-YYYY')

=>10-Aug-2010

DateFormatter.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')

=>2017-11-22 19:52:37

DateFormatter.formatDate(new Date(2005, 1, 2, 3, 4, 5), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A')

=>2 02 Wed Wednesday, 2 02 Feb February, 05 2005, 3 03 3 03, 4 04, 5 05, am AM

var DateFormatter = {
  monthNames: [
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  ],
  dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
  formatDate: function (date, format) {
    var self = this;
    format = self.getProperDigits(format, /d+/gi, date.getDate());
    format = self.getProperDigits(format, /M+/g, date.getMonth() + 1);
    format = format.replace(/y+/gi, function (y) {
      var len = y.length;
      var year = date.getFullYear();
      if (len == 2)
        return (year + "").slice(-2);
      else if (len == 4)
        return year;
      return y;
    })
    format = self.getProperDigits(format, /H+/g, date.getHours());
    format = self.getProperDigits(format, /h+/g, self.getHours12(date.getHours()));
    format = self.getProperDigits(format, /m+/g, date.getMinutes());
    format = self.getProperDigits(format, /s+/gi, date.getSeconds());
    format = format.replace(/a/ig, function (a) {
      var amPm = self.getAmPm(date.getHours())
      if (a === 'A')
        return amPm.toUpperCase();
      return amPm;
    })
    format = self.getFullOr3Letters(format, /d+/gi, self.dayNames, date.getDay())
    format = self.getFullOr3Letters(format, /M+/g, self.monthNames, date.getMonth())
    return format;
  },
  getProperDigits: function (format, regex, value) {
    return format.replace(regex, function (m) {
      var length = m.length;
      if (length == 1)
        return value;
      else if (length == 2)
        return ('0' + value).slice(-2);
      return m;
    })
  },
  getHours12: function (hours) {
    // https://stackoverflow.com/questions/10556879/changing-the-1-24-hour-to-1-12-hour-for-the-gethours-method
    return (hours + 24) % 12 || 12;
  },
  getAmPm: function (hours) {
    // https://stackoverflow.com/questions/8888491/how-do-you-display-javascript-datetime-in-12-hour-am-pm-format
    return hours >= 12 ? 'pm' : 'am';
  },
  getFullOr3Letters: function (format, regex, nameArray, value) {
    return format.replace(regex, function (s) {
      var len = s.length;
      if (len == 3)
        return nameArray[value].substr(0, 3);
      else if (len == 4)
        return nameArray[value];
      return s;
    })
  }
}

console.log(DateFormatter.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss'));
console.log(DateFormatter.formatDate(new Date(), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A'));
console.log(DateFormatter.formatDate(new Date(2005, 1, 2, 3, 4, 5), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A'));
Run Code Online (Sandbox Code Playgroud)

格式描述取自Ionic Framework(它不支持Z, UTC 时区偏移)

没有经过彻底测试


K V*_*Vij 5

截至2019年,您似乎可以获取toLocaleDateString仅返回某些部分,然后可以根据需要加入它们:

var date = new Date();

console.log(date.toLocaleDateString("en-US", { day: 'numeric' }) 
            + "-"+ date.toLocaleDateString("en-US", { month: 'short' })
            + "-" + date.toLocaleDateString("en-US", { year: 'numeric' }) );

> 16-Nov-2019

console.log(date.toLocaleDateString("en-US", { month: 'long' }) 
            + " " + date.toLocaleDateString("en-US", { day: 'numeric' }) 
            + ", " + date.toLocaleDateString("en-US", { year: 'numeric' }) );

> November 16, 2019
Run Code Online (Sandbox Code Playgroud)


Kam*_*ski 5

两个纯 JS 单行

在这个答案中,我发展了JD Smith 的想法。我能够缩短 JD Smith regexp

let format= d=> d.toString().replace(/\w+ (\w+) (\d+) (\d+).*/,'$2-$1-$3');

console.log( format(Date()) );
Run Code Online (Sandbox Code Playgroud)

Dave也基于 JD Smith 的想法,但他避免使用正则表达式并提供非常好的解决方案 - 我缩短了他的解决方案(通过更改拆分参数)并将其在包装器中不透明

let format= (d,a=d.toString().split` `)=> a[2]+"-"+a[1]+"-"+a[3];

console.log( format(Date()) );
Run Code Online (Sandbox Code Playgroud)


Tom*_*Tom 5

在 IE 11、FF 和 Chrome 中工作相同(Chrome 80.x 在选择 en-UK 时显示 12 小时格式)。

const d = new Date('2010/08/05 23:45') // 26.3.2020
const dtfUK = new Intl.DateTimeFormat('UK', { year: 'numeric', month: '2-digit', day: '2-digit',
        hour: '2-digit',minute: '2-digit', second: '2-digit' }); //
const dtfUS = new Intl.DateTimeFormat('en', { year: 'numeric', month: '2-digit', day: '2-digit',
        hour: '2-digit',minute: '2-digit', second: '2-digit' }); //
console.log(dtfUS.format(d)); // 08/05/2010 11:45:00 PM
console.log(dtfUK.format(d)); // 05.08.2010 23:45:00
/* node.js:
08/05/2010, 11:45:00 PM
2010-08-05 23:45:00
*/
Run Code Online (Sandbox Code Playgroud)

更一般的东西呢?

var d = new Date('2010-08-10T10:34:56.789Z');
var str = d.toDateString() + // Tue Aug 10 2010
    ' ' + d.toTimeString().split(' ')[0] + // 12:34:56, GMT+0x00 (GMT+0x:00)
    ' ' + (d.getMonth() + 101) + // 108
    ' ' + d.getMilliseconds(); // 789
console.log(str); // Tue Aug 10 2010 12:34:56 108 789
console.log(//   $1 Tue  $2 Aug  $3 11     $4 2020 $5 12   $6 34   $7 56    $8 108  $9 789
    str.replace(/(\S{3}) (\S{3}) (\d{1,2}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) 1(\d{2}) (\d{1,3})/, '$3-$2-$4 $5:$6.$9 ($1)')
); // 10-Aug-2010 12:34.789 (Tue)
/*
$1: Tue  Week Day string
$2: Aug  Month short text
$3: 11   Day
$4: 2010 Year
$5: 12   Hour
$6: 34   Minute
$7: 56   Seconds
$8: 08   Month
$9: 789  Milliseconds
*/
Run Code Online (Sandbox Code Playgroud)

或者例如 1-line IIFE "library" ;-)

console.log(
    (function (frm, d) { return [d.toDateString(), d.toTimeString().split(' ')[0], (d.getMonth() + 101), d.getMilliseconds()].join(' ').replace(/(\S{3}) (\S{3}) (\d{1,2}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) 1(\d{2}) (\d{1,3})/, frm); })
    ('$4/$8/$3 $5:$6 ($1)', new Date())
);
Run Code Online (Sandbox Code Playgroud)

如果您不需要它们,您可以删除无用的部分和/或更改索引。


Kam*_*mov 5

示例:“2023-04-25 00:01:23”

var currentdate = new Date();
var startedAt = currentdate.getFullYear() + "-" +
    (currentdate.getMonth() + 1).toString().padStart(2, '0') + "-" +
    currentdate.getDate().toString().padStart(2, '0') + " " +
    currentdate.getHours().toString().padStart(2, '0') + ":" +
    currentdate.getMinutes().toString().padStart(2, '0') + ":" +
    currentdate.getSeconds().toString().padStart(2, '0');
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

3316585 次

最近记录:

5 年,9 月 前