我在哪里可以find关于在JavaScript中格式化date的文档?

我注意到JavaScript的new Date()函数在接受多种格式的date方面非常聪明。

 Xmas95 = new Date("25 Dec, 1995 23:15:00") Xmas95 = new Date("2009 06 12,12:52:39") Xmas95 = new Date("20 09 2006,12:52:39") 

在调用new Date()函数时,我无法在任何地方find显示所有有效string格式的文档。

这是将string转换为date。 如果我们看另一面,也就是将date对象转换为string,直到现在,我还是觉得JavaScript没有内置API来将date对象格式化为string。

编者注:以下方法是提问者在特定浏览器上的尝试,但一般不起作用; 看到在这个页面上的答案 ,看到一些实际的解决scheme。

今天,我在date对象上使用了toString()方法,而且令人惊讶的是,它将date格式化为string。

 var d1 = new Date(); d1.toString('yyyy-MM-dd'); //Returns "2009-06-29" in Internet Explorer, but not Firefox or Chrome d1.toString('dddd, MMMM ,yyyy') //Returns "Monday, June 29,2009" in Internet Explorer, but not Firefox or Chrome 

另外在这里,我找不到任何有关我们可以将date对象格式化为string的任何文档。

列出Date()对象支持的格式说明符的文档在哪里?

我喜欢使用JavaScript使用date 来格式化时间和date的10种方法

基本上,你有三种方法,你必须结合自己的string:

 getDate() // Returns the date getMonth() // Returns the month getFullYear() // Returns the year 

例:

 <script type="text/javascript"> var d = new Date(); var curr_date = d.getDate(); var curr_month = d.getMonth() + 1; //Months are zero based var curr_year = d.getFullYear(); console.log(curr_date + "-" + curr_month + "-" + curr_year); </script> 

Moment.js

这是一个(轻量级)JavaScriptdate库,用于parsing,操作和格式化date。

 var a = moment([2010, 1, 14, 15, 25, 50, 125]); a.format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm" a.format("ddd, hA"); // "Sun, 3PM" 

(*)轻量级的意思9.3KB缩小+ gzipped在最小的可能设置(二月2014)

如果您已经在项目中使用jQuery UI ,则可以使用内置的datepicker方法来设置date对象的格式:

 $.datepicker.formatDate('yy-mm-dd', new Date(2007, 1 - 1, 26)); 

但是,dateselect器只格式化date,不能格式化时间。

看看jQuery UI datepicker formatDate的例子。

列出Date()对象支持的格式说明符的文档在哪里?

我今天偶然发现了这个,很惊讶没有人花时间来回答这个简单的问题。 没错,有很多图书馆可以帮助你处理date。 有些人比别人好。 但这不是问的问题。

AFAIK,纯JavaScript不支持格式说明符的方式,你已经表示你想使用它们 。 但它支持格式化date和/或时间的方法,如.toLocaleDateString() .toLocaleTimeString().toUTCString()

我使用最频繁的Date对象引用是在w3schools.com网站上 (但是快速的Googlesearch将揭示更多可以更好地满足您的需求)。

另请注意, Date对象属性部分提供了一个prototype链接,该链接说明了使用自定义方法扩展Date对象的一些方法。 JavaScript社区多年来一直在争论这是否是最佳实践,我并不是主张或反对,只是指出它的存在。

自定义格式function:

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

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

注意:但是,扩展Javascript标准库通常不是一个好主意(例如,将这个函数添加到Date的原型中)。

更高级的function可以基于格式参数生成可configuration的输出。 在同一页面中有几个很好的例子。

如果写一个格式化函数太长了,那么这个库有很多的库。 其他一些答案已经列举了他们。 但是越来越多的依赖关系也有其相反的地方。

标准ECMAScript格式化function:

由于更新版本的ECMAscript, Date类具有一些特定的格式化function:

toDateString :依赖于实现,只显示date。

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

 new Date().toDateString(); // eg "Fri Nov 11 2016" 

toISOString :显示ISO 8601的date和时间。

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

 new Date().toISOString(); // eg "2016-11-21T08:00:00.000Z" 

toJSON :JSON的string。

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

 new Date().toJSON(); // eg "2016-11-21T08:00:00.000Z" 

toLocaleDateString :依赖于实现,一个以区域设置格式的date。

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

 new Date().toLocaleDateString(); // eg "21/11/2016" 

toLocaleString :依赖于实现,以区域设置格式显示date和时间。

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

 new Date().toLocaleString(); // eg "21/11/2016, 08:00:00 AM" 

toLocaleTimeString :实现相关的,一个时间区域设置格式。

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

 new Date().toLocaleTimeString(); // eg "08:00:00 AM" 

toString :date的通用toString。

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

 new Date().toString(); // eg "Fri Nov 11 2016 08:00:00 GMT+0100 (W. Europe Standard Time)" 

注意:可以从这些格式化函数中生成自定义输出:

 new Date().toISOString().slice(0,10); // By @Image72, return YYYY-MM-DD 

简答题

没有javascript支持的“通用”文档; 每个具有JavaScript的浏览器都是一个实现。 但是,大多数现代浏览器往往遵循一个标准,那就是EMCAScript标准。 ECMAScript标准string最less会采用ISO 8601定义的修改实现。

除此之外, IETF还提出了另一个标准,即浏览器也遵循RFC 2822中定义的时间戳。实际文档可以在底部的参考列表中find。

从这里你可以期待基本的function,但“应该”是什么本质上不是“是”。 不过,我会用这个程序深入一点,因为看起来只有三个人真的回答了这个问题(Scott,goballball,and peller),对我而言,build议大多数人不知道当你创build一个Date对象。


长的答案

列出Date()对象支持的格式说明符的文档在哪里?

为了回答这个问题,或者通常甚至寻找这个问题的答案,你需要知道JavaScript不是一种新颖的语言; 它实际上是一个ECMAScript的实现,并且遵循ECMAScript标准(但是注意,JavaScript实际上也是在这些标准之前的; EMCAScript标准是build立在LiveScript / JavaScript的早期实现之外的)。 目前的ECMAScript标准是5.1(2011); 最初问(09年6月)的时候,标准是3(4被放弃),但在2009年底之后不久就发布了5个。 什么是标准的JavaScript实现可能遵循,可能不反映实际到位,因为a)它是一个给定的标准的实现,b)标准的所有实现不清洁,c)function不是与新标准d)实施是一项持续不断的工作

从本质上讲,在处理JavaScript时,你正在处理一个实现(javascript本身)的派生(JavaScript特有的浏览器)。 例如,Google的V8实现了ECMAScript 5.0,但Internet Explorer的JScript并不试图符合任何ECMAScript标准,但Internet Explorer 9确实符合ECMAScript 5.0。

当一个parameter passing给新的Date()时,它会投射这个函数原型:

 new Date(value) 

当两个或更多的parameter passing给新的Date()时,它会投射这个函数原型:

 new Date (year, month [, date [, hours [, minutes [, seconds [, ms ] ] ] ] ] ) 

这两个函数都应该看起来很熟悉,但是这并不能立即回答你的问题,作为可接受的“date格式”量化的东西需要进一步的解释。 当你将一个string传递给新的Date()时,它会调用原型(注意,我使用松散的单词原型 ;版本可能是单个函数,或者它可能是单个函数中的条件语句的一部分) 新的date(值)与您的string作为“值”参数的参数。 这个函数首先会检查它是一个数字还是一个string。 这个function的文档可以在这里find:

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.3.2

由此我们可以推断,为了获得新的Date(value)所允许的string格式,我们必须查看Date.parse(string)方法。 这个方法的文档可以在这里find:

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.4.2

而且我们可以进一步推断,date预计是在一个修改的ISO 8601扩展格式,如下所示:

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15

然而,我们可以从经验中认识到,JavaScript的Date对象接受其他格式(首先由这个问题的存在强制执行),这是可以的,因为ECMAScript允许实现特定的格式。 但是,这仍然不能回答在可用格式上有哪些文档可用的问题,也不能回答实际允许的格式。 我们将看看Google的JavaScript实现,V8; 请注意,我并不是build议这是“最好”的JavaScript引擎(如何定义“最好”,甚至“好”),而且不能认为V8中允许的格式代表当前所有可用格式,但我认为这是公平的假设他们确实遵循现代的期望。

Google的V8,date.js,DateConstructor

https://code.google.com/p/v8/source/browse/trunk/src/date.js?r=18400#141

查看DateConstructor函数,我们可以推断我们需要findDateParse函数; 但是请注意,“年份”不是实际的年份,只是“年份”参数的参考。

Google的V8,date.js,DateParse

https://code.google.com/p/v8/source/browse/trunk/src/date.js?r=18400#270

这将调用%DateParseString,这实际上是C ++函数的运行时函数引用。 它是指以下代码:

Google的V8,runtime.cc,%DateParseString

https://code.google.com/p/v8/source/browse/trunk/src/runtime.cc?r=18400#9559

我们在这个函数中关心的函数调用是DateParser :: Parse(); 忽略这些函数调用的逻辑,这些只是检查符合编码types(ASCII和UC16)。 DateParser :: Parse在这里定义:

Google的V8,dateparser-inl.h,DateParser :: Parse

https://code.google.com/p/v8/source/browse/trunk/src/dateparser-inl.h?r=18400#36

这是实际定义接受的格式的函数。 本质上,它检查EMCAScript 5.0 ISO 8601标准,如果它不符合标准,则将尝试基于传统格式构builddate。 基于评论的几点要点:

  1. parsing器未知的第一个数字之前的单词被忽略。
  2. 括号内的文字被忽略。
  3. 无符号数字后跟“:”被解释为“时间成分”。
  4. 无符号数字后跟“。”被解释为“时间成分”,并且必须跟随毫秒。
  5. 带符号的数字后跟小时或分钟(例如+5:15或+0515)被解释为时区。
  6. 声明小时和分钟时,可以使用“hh:mm”或“hhmm”。
  7. 指示时区的词语被解释为时区。
  8. 所有其他数字被解释为“date组件”。
  9. 所有以月份前三位开头的单词都被解释为月份。
  10. 您可以使用两种格式中的任意一种来定义分钟和小时:“hh:mm”或“hhmm”。
  11. 数字已被处理后,不允许使用符号“+”,“ – ”和不匹配的“)”。
  12. 匹配多种格式的项目(例如1970-01-01)将作为符合标准的EMCAScript 5.0 ISO 8601string进行处理。

所以这应该足以给你一个关于将string传递给Date对象的期望的基本概念。 您可以通过查看Mozilla指向Mozilla开发者networking(符合IETF RFC 2822时间戳)的以下规范来进一步扩展:

http://tools.ietf.org/html/rfc2822#page-14

Microsoft开发人员networking另外提到了Date对象的附加标准:ECMA-402,即ECMAScript国际化API规范,它与ECMAScript 5.1标准(以及将来的)是互补的。 这可以在这里find:

http://www.ecma-international.org/ecma-402/1.0/

在任何情况下,这应该有助于强调没有通用的表示所有JavaScript实现的“文档”,但是仍然有足够的文档可以合理地理解Date对象可以接受哪些string。 当你想到这个问题时,是不是有问题? :P

参考

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.3.2

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.4.2

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15

http://tools.ietf.org/html/rfc2822#page-14

http://www.ecma-international.org/ecma-402/1.0/

https://code.google.com/p/v8/source/browse/trunk/src/date.js?r=18400#141

https://code.google.com/p/v8/source/browse/trunk/src/date.js?r=18400#270

https://code.google.com/p/v8/source/browse/trunk/src/runtime.cc?r=18400#9559

https://code.google.com/p/v8/source/browse/trunk/src/dateparser-inl.h?r=18400#36

资源

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

http://msdn.microsoft.com/en-us/library/ff743760(v=vs.94).aspx

确保在JavaScript中处理date时检出Datejs 。 这是相当令人印象深刻的,并有良好的文件,你可以看到toString函数的情况下。

编辑 :Tyler Forsythe指出,那datejs是过时的。 我在当前的项目中使用它,并没有任何问题,但你应该知道这一点,并考虑替代品。

您可以使用meizz所示的新format方法来扩展Date对象,下面是作者给出的代码。 这里是一个jsfiddle 。

 Date.prototype.format = function(format) //author: meizz { var o = { "M+" : this.getMonth()+1, //month "d+" : this.getDate(), //day "h+" : this.getHours(), //hour "m+" : this.getMinutes(), //minute "s+" : this.getSeconds(), //second "q+" : Math.floor((this.getMonth()+3)/3), //quarter "S" : this.getMilliseconds() //millisecond } if(/(y+)/.test(format)) format=format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); for(var k in o)if(new RegExp("("+ k +")").test(format)) format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length)); return format; } alert(new Date().format("yyyy-MM-dd")); alert(new Date("january 12 2008 11:12:30").format("yyyy-MM-dd h:mm:ss")); 

你所引用的function不是标准的Javascript,不可能跨浏览器移植,因此也不是很好的做法。 ECMAScript 3规范将parsing和输出格式的function留给了Javascript实现。 ECMAScript 5添加了ISO8601支持的一个子集。 我相信你提到的toString()函数是一个浏览器中的创新(Mozilla?)

有几个库提供例程来对此进行参数化,一些库提供了广泛的本地化支持。 你也可以查看dojo.date.locale中的方法。

我做了这个非常简单的格式化程序,它被剪切/ n /可粘贴(更新与整洁的版本):

 function DateFmt(fstr) { this.formatString = fstr var mthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]; var dayNames = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]; var zeroPad = function(number) { return ("0"+number).substr(-2,2); } var dateMarkers = { d:['getDate',function(v) { return zeroPad(v)}], m:['getMonth',function(v) { return zeroPad(v+1)}], n:['getMonth',function(v) { return mthNames[v]; }], w:['getDay',function(v) { return dayNames[v]; }], y:['getFullYear'], H:['getHours',function(v) { return zeroPad(v)}], M:['getMinutes',function(v) { return zeroPad(v)}], S:['getSeconds',function(v) { return zeroPad(v)}], i:['toISOString'] }; this.format = function(date) { var dateTxt = this.formatString.replace(/%(.)/g, function(m, p) { var rv = date[(dateMarkers[p])[0]]() if ( dateMarkers[p][1] != null ) rv = dateMarkers[p][1](rv) return rv }); return dateTxt } } fmt = new DateFmt("%w %d:%n:%y - %H:%M:%S %i") v = fmt.format(new Date()) 

http://snipplr.com/view/66968.82825/

免费的框架,有限但轻

 var d = (new Date()+'').split(' '); // ["Tue", "Sep", "03", "2013", "21:54:52", "GMT-0500", "(Central", "Daylight", "Time)"] [d[3], d[1], d[2], d[4]].join(' '); // "2013 Sep 03 21:58:03" 

DateJS当然是全function的,但我推荐这个更简单的lib(JavaScriptdate格式) ,我更喜欢它,因为它只有120行左右。

查看了其他答案中提供的几个选项后,我决定编写自己的有限但简单的解决scheme,其他人也可能会发现有用。

 /** * Format date as a string * @param date - a date object (usually "new Date();") * @param format - a string format, eg. "DD-MM-YYYY" */ function dateFormat(date, format) { // Calculate date parts and replace instances in format string accordingly format = format.replace("DD", (date.getDate() < 10 ? '0' : '') + date.getDate()); // Pad with '0' if needed format = format.replace("MM", (date.getMonth() < 9 ? '0' : '') + (date.getMonth() + 1)); // Months are zero-based format = format.replace("YYYY", date.getFullYear()); return format; } 

用法示例:

 console.log("The date is: " + dateFormat(new Date(), "DD/MM/YYYY")); 

这是我用了很多的function。 结果是yyyy-mm-dd hh:mm:ss.nnn。

 function date_and_time() { var date = new Date(); //zero-pad a single zero if needed var zp = function (val){ return (val <= 9 ? '0' + val : '' + val); } //zero-pad up to two zeroes if needed var zp2 = function(val){ return val <= 99? (val <=9? '00' + val : '0' + val) : ('' + val ) ; } var d = date.getDate(); var m = date.getMonth() + 1; var y = date.getFullYear(); var h = date.getHours(); var min = date.getMinutes(); var s = date.getSeconds(); var ms = date.getMilliseconds(); return '' + y + '-' + zp(m) + '-' + zp(d) + ' ' + zp(h) + ':' + zp(min) + ':' + zp(s) + '.' + zp2(ms); } 

您可能会发现对date对象的修改很有用,它比任何库都小,并且可以轻松扩展以支持不同的格式:

注意:

  • 它使用旧版浏览器中未定义的Object.keys() ,因此您可能需要从给定的链接实现填充。

 Date.prototype.format = function(format) { // set default format if function argument not provided format = format || 'YYYY-MM-DD hh:mm'; var zeropad = function(number, length) { number = number.toString(); length = length || 2; while(number.length < length) number = '0' + number; return number; }, // here you can define your formats formats = { YYYY: this.getFullYear(), MM: zeropad(this.getMonth() + 1), DD: zeropad(this.getDate()), hh: zeropad(this.getHours()), mm: zeropad(this.getMinutes()) }, pattern = '(' + Object.keys(formats).join(')|(') + ')'; return format.replace(new RegExp(pattern, 'g'), function(match) { return formats[match]; }); }; 

使用

 var now = new Date; console.log(now.format()); // outputs: 2015-02-09 11:47 var yesterday = new Date('2015-02-08'); console.log(yesterday.format('hh:mm YYYY/MM/DD')); // outputs: 00:00 2015/02/08 

Just to continue gongzhitaao's solid answer – this handles AM/PM

  Date.prototype.format = function (format) //author: meizz { var hours = this.getHours(); var ttime = "AM"; if(format.indexOf("t") > -1 && hours > 12) { hours = hours - 12; ttime = "PM"; } var o = { "M+": this.getMonth() + 1, //month "d+": this.getDate(), //day "h+": hours, //hour "m+": this.getMinutes(), //minute "s+": this.getSeconds(), //second "q+": Math.floor((this.getMonth() + 3) / 3), //quarter "S": this.getMilliseconds(), //millisecond, "t+": ttime } if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); return format; } 

Formatting and especially parsing dates in JavaScript can be a bit of a headache. Not all browsers handle dates in the same way. So while it's useful to know the base methods, its more practical to use a helper library.

The XDate javascript library by Adam Shaw has been around since mid-2011 and is still under active development. It has fantastic documentation, a great API, formatting, tries to remain backwards-compatible and even supports localized strings.

Link to changing the locale strings: https://gist.github.com/1221376

示例代码:

 var d = new Date(); var time = d.toISOString().replace(/.*?T(\d+:\d+:\d+).*/, "$1"); 

输出:

"13:45:20"

I was unable to find any definitive documentation on valid date formats so I wrote my own test to see what is supported in various browsers.

http://blarg.co.uk/blog/javascript-date-formats

My results concluded the following formats are valid in all browsers that I tested (examples use the date "9th August 2013"):

[Full Year]/[Month]/[Date number] – Month can be either the number with or without a leading zero or the month name in short or long format, and date number can be with or without a leading zero.

  • 2013年8月9日
  • 2013/08/9
  • 2013/8/09
  • 2013/8/9
  • 2013/August/09
  • 2013/August/9
  • 2013/Aug/09
  • 2013/Aug/9

[Month]/[Full Year]/[Date Number] – Month can be either the number with or without a leading zero or the month name in short or long format, and date number can be with or without a leading zero.

  • 08/2013/09
  • 08/2013/9
  • 8/2013/09
  • 8/2013/9
  • August/2013/09
  • August/2013/9
  • Aug/2013/09
  • Aug/2013/9

Any combination of [Full Year], [Month Name] and [Date Number] separated by spaces – Month name can be in either short or long format, and date number can be with or without a leading zero.

  • 2013 August 09
  • August 2013 09
  • 09 August 2013
  • 2013 Aug 09
  • Aug 9 2013
  • 2013 9 Aug
  • 等等…

Also valid in "modern browsers" (or in other words all browsers except IE9 and below)

[Full Year]-[Month Number]-[Date Number] – Month and Date Number must include leading zeros (this is the format that the MySQL Date type uses)

  • 2013-08-09

Using month names:
Interestingly, when using month names I discovered that only the first 3 characters of the month name are ever used so all the of the following are perfectly valid:

 new Date('9 August 2013'); new Date('9 Aug 2013'); new Date('9 Augu 2013'); new Date('9 Augustagfsdgsd 2013'); 

The library sugar.js has some great functionality for working with dates in JavaScript. And it is very well documented .

Sugar gives the Date class much love starting with the Date.create method which can understand dates in just about any format in 15 major languages, including relative formats like "1 hour ago". Dates can also be output in any format or language using an easy to understand syntax, with shortcuts to commonly used date formats. Complex date comparison is also possible with methods like is, which understand any format and apply built in precision.

几个例子:

 Date.create('July 4, 1776') -> July 4, 1776 Date.create(-446806800000) -> November 5, 1955 Date.create(1776, 6, 4) -> July 4, 1776 Date.create('1776年07月04日', 'ja') -> July 4, 1776 Date.utc.create('July 4, 1776', 'en') -> July 4, 1776 Date.create().format('{Weekday} {d} {Month}, {yyyy}') -> Monday July 4, 2003 Date.create().format('{hh}:{mm}') -> 15:57 Date.create().format('{12hr}:{mm}{tt}') -> 3:57pm Date.create().format(Date.ISO8601_DATETIME) -> 2011-07-05 12:24:55.528Z Date.create().is('the 7th of June') -> false Date.create().addMonths(2); ->"Sunday, June 15, 2014 13:39" 

只是另一个select,我写道:

DP_DateExtensions库

Not sure if it'll help, but I've found it useful in several projects – looks like it'll do what you need.

支持date/时间格式,datemath(加/减date部分),date比较,date分析等。它是自由开源。

No reason to consider it if you're already using a framework (they're all capable), but if you just need to quickly add date manipulation to a project give it a chance.

The correct way to format a date to return "2012-12-29" is with the script from JavaScript Date Format :

 var d1 = new Date(); return d1.format("dd-m-yy"); 

This code does NOT work:

 var d1 = new Date(); d1.toString('yyyy-MM-dd'); 

If you want to show only time with two digits, this may helps you:

 var now = new Date(); var cHour = now.getHours(); var cMinuts = now.getMinutes(); var cSeconds = now.getSeconds(); var outStr = (cHour <= 0 ? ('0' + cHour) : cHour) + ':' + (cMinuts <= 9 ? ('0' + cMinuts) : cMinuts) + ':' + (cSeconds <= 9 ? '0' + cSeconds : cSeconds); 

JsSimpleDateFormat is a library that can format the date object and parse the formatted string back to Date object. It uses the Java format (SimpleDateFormat class). The name of months and days can be localized.

例:

 var sdf = new JsSimpleDateFormat("EEEE, MMMM dd, yyyy"); var formattedString = sdf.format(new Date()); var dateObject = sdf.parse("Monday, June 29, 2009"); 

use this functions

 toTimeString() and toLocaleDateString() 

refer below link for more details https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Personally, because I use both PHP and jQuery/javascript in equal measures, I use the date function from php.js http://phpjs.org/functions/date/

Using a library that uses the same format strings as something I already know is easier for me, and the manual containing all of the format string possibilities for the date function is of course online at php.net

You simply include the date.js file in your HTML using your preferred method then call it like this:

 var d1=new Date(); var datestring = date('Ym-d', d1.valueOf()/1000); 

You can use d1.getTime() instead of valueOf() if you want, they do the same thing.

The divide by 1000 of the javascript timestamp is because a javascript timestamp is in miliseconds but a PHP timestamp is in seconds.

See dtmFRM.js . If you are familiar with C#'s custom date and time format string, this library should do the exact same thing.

DEMO :

 var format = new dtmFRM(); var now = new Date().getTime(); $('#s2').append(format.ToString(now,"This month is : MMMM") + "</br>"); $('#s2').append(format.ToString(now,"Year is : y or yyyy or yy") + "</br>"); $('#s2').append(format.ToString(now,"mm/yyyy/dd") + "</br>"); $('#s2').append(format.ToString(now,"dddd, MM yyyy ") + "</br>"); $('#s2').append(format.ToString(now,"Time is : hh:mm:ss ampm") + "</br>"); $('#s2').append(format.ToString(now,"HH:mm") + "</br>"); $('#s2').append(format.ToString(now,"[ddd,MMM,d,dddd]") + "</br></br>"); now = '11/11/2011 10:15:12' ; $('#s2').append(format.ToString(now,"MM/dd/yyyy hh:mm:ss ampm") + "</br></br>"); now = '40/23/2012' $('#s2').append(format.ToString(now,"Year is : y or yyyy or yy") + "</br></br>"); 

If you don't need all the features that a library like Moment.js provides, 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() .

 /* 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() { if (nYear&3!==0) return false; return nYear%100!==0 || year%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(/%[az]/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; }); } 

Sample usage:

 strftime('%F'); // Returns "2016-09-15" strftime('%A, %B %e, %Y'); // Returns "Thursday, September 15, 2016" // You can optionally pass it a Date object... strftime('%x %X', new Date('1/1/2016')); // Returns "1/1/2016 12:00:00 AM" 

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

The answer is "nowhere" since the date formatting is proprietary functionality. I don't think the toString functions are intended to conform to a specific format. eg in the ECMAScript 5.1 spec ( publications/files/ECMA-ST/Ecma-2622.html , 2/8/2013, page 173), the toString function is documented as follows:

"The contents of the String are implementation-dependent"

Functions such as the samples below could be used to accomplish formatting fairly easily.

 function pad(toPad, padWith) { return (String(padWith) + String(toPad)).slice(-1 * padWith.length); } function dateAsInputValue(toFormat) { if(!(toFormat instanceof Date)) return null; return toFormat.getFullYear() + "-" + pad(toFormat.getMonth() + 1, "00") + "-" + pad(toFormat.getDate(), "00"); } function timeAsInputValue(toFormat) { if(!(toFormat instanceof Date)) return null; return pad(toFormat.getHours(), "00") + ":" + pad(toFormat.getMinutes(), "00") + ":" + pad(toFormat.getSeconds(), "00"); } 

Many frameworks (that you might already be using) have date formatting that you may not be aware of. jQueryUI was already mentioned, but other frameworks such as Kendo UI (Globalization) , Yahoo UI (Util) and AngularJS have them as well.

 // 11/6/2000 kendo.toString(new Date(value), "d") // Monday, November 06, 2000 kendo.toString(new Date(2000, 10, 6), "D")