在哪里可以找到有关在JavaScript中格式化日期的文档?
我注意到JavaScript的在哪里可以找到有关在JavaScript中格式化日期的文档?,javascript,date,Javascript,Date,我注意到JavaScript的newdate()函数在接受多种格式的日期方面非常聪明 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") 调用newdate()函数时,我在任何地方都找不到显示所有有效字符串格式的文档 这用于将字符串转换为日期。如果我们看另一面,也就是将日期对象转换为字符串,直到现在
newdate()
函数在接受多种格式的日期方面非常聪明
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")
调用newdate()
函数时,我在任何地方都找不到显示所有有效字符串格式的文档
这用于将字符串转换为日期。如果我们看另一面,也就是将日期对象转换为字符串,直到现在,我的印象是JavaScript没有内置API将日期对象格式化为字符串
编者按:以下方法是询问者在特定浏览器上的尝试,但通常不起作用查看本页的答案查看一些实际解决方案
今天,我在date对象上使用了toString()
方法,令人惊讶的是,它用于将日期格式化为字符串
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()
对象支持的格式说明符?我喜欢和
基本上,您有三种方法,您必须自己组合字符串:
getDate() // Returns the date
getMonth() // Returns the month
getFullYear() // Returns the year
例如:
var sdf = new JsSimpleDateFormat("EEEE, MMMM dd, yyyy");
var formattedString = sdf.format(new Date());
var dateObject = sdf.parse("Monday, June 29, 2009");
var d=新日期();
var curr_date=d.getDate();
var curr_month=d.getMonth()+1//月份是以零为基础的
var curr_year=d.getFullYear();
控制台日志(当前日期+“-”+当前月份+“-”+当前年份)代码>确保在处理JavaScript中的日期时签出。这是相当令人印象深刻的,并且有很好的文档记录,正如你们在案例中看到的
编辑:泰勒·福赛斯指出,datejs已经过时了。我在我的当前项目中使用它,并且没有任何问题,但是你应该意识到这一点并考虑其他的选择。 < P>另一个选项,我写的:
不确定它是否有用,但我发现它在几个项目中很有用——看起来它可以满足您的需要
支持日期/时间格式、日期数学(添加/减去日期部分)、日期比较、日期解析等。它是开源的
如果你已经使用了一个框架(它们都是有能力的),没有理由去考虑它,但是如果你只需要快速地将一个项目添加到一个项目中,给它一个机会。 你引用的功能不是标准的JavaScript,不可能在浏览器上是可移植的,因此不是很好的实践。解析和输出格式的功能由Javascript实现决定。添加ISO8601支持的子集。我相信您提到的toString()函数是一款浏览器的创新(Mozilla?)
有几个库提供了参数化的例程,有些库提供了广泛的本地化支持。您还可以查看中的方法。如果您已经在项目中使用,则可以使用内置的datepicker方法格式化日期对象:
$.datepicker.formatDate('yy-mm-dd', new Date(2007, 1 - 1, 26));
但是,datepicker只能格式化日期,不能格式化时间
看看这些例子。DateJS当然功能齐全,但我还是推荐我更喜欢的,因为它只有120行左右。在JavaScript中格式化,尤其是解析日期可能有点头疼。并非所有浏览器都以相同的方式处理日期。因此,虽然了解基本方法很有用,但使用助手库更为实用
by从2011年年中开始运作,目前仍在积极开发中。它有很棒的文档,一个很棒的API,格式化,试图保持向后兼容,甚至支持本地化字符串
更改区域设置字符串的链接:
它是一个(轻量级)*JavaScript日期库,用于解析、操作和格式化日期
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"
(*)轻量级意味着在尽可能小的设置(2014年2月)中压缩了9.3KB+gzip。是一个可以格式化日期对象并将格式化字符串解析回日期对象的库。它使用Java格式(SimpleDataFormat类)。月份和天数的名称可以本地化
例如:
var sdf = new JsSimpleDateFormat("EEEE, MMMM dd, yyyy");
var formattedString = sdf.format(new Date());
var dateObject = sdf.parse("Monday, June 29, 2009");
自定义格式功能:
对于固定格式,只需一个简单的函数即可完成此任务。以下示例生成国际格式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);
}
toISOString:显示ISO 8601日期和时间
toJSON:JSON的字符串化器
toLocaleDateString:依赖于实现,是区域设置格式的日期
toLocaleString:依赖于实现,是区域设置格式的日期和时间
toLocaleTimeString:依赖于实现,是区域设置格式的时间
toString:日期的通用toString
注意:可以使用这些格式化函数生成自定义输出:
new Date().toISOString().slice(0,10); // By @Image72, return YYYY-MM-DD
列出Date()
对象支持的格式说明符的文档在哪里
我今天偶然发现了这个问题,很惊讶没有人花时间回答这个简单的问题。的确,有很多库可以帮助处理日期。有些比另一些好。但这不是问题所在
好吧,纯JavaScript不支持格式说明符,就像您所表示的那样使用它们。但它确实支持格式化日期和/或时间的方法,例如.toLocaleDateString()
,.toLocaleTimeString()
,和.toutString()
我最常使用的日期
对象引用位于上(但将显示更多可能更好地满足您需求的内容)
还请注意,日期对象属性部分提供了到的链接,其中说明了使用自定义方法扩展日期对象的一些方法。在JavaScript社区中已经出现了一些问题
new Date().toJSON(); // e.g. "2016-11-21T08:00:00.000Z"
new Date().toLocaleDateString(); // e.g. "21/11/2016"
new Date().toLocaleString(); // e.g. "21/11/2016, 08:00:00 AM"
new Date().toLocaleTimeString(); // e.g. "08:00:00 AM"
new Date().toString(); // e.g. "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
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())
/**
* 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"));
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"));
var d1 = new Date();
return d1.format("dd-m-yy");
var d1 = new Date();
d1.toString('yyyy-MM-dd');
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");
}
var d1=new Date();
var datestring = date('Y-m-d', d1.valueOf()/1000);
// 11/6/2000
kendo.toString(new Date(value), "d")
// Monday, November 06, 2000
kendo.toString(new Date(2000, 10, 6), "D")
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);
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;
}
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"
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"
var d = new Date();
var time = d.toISOString().replace(/.*?T(\d+:\d+:\d+).*/, "$1");
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);
}
new Date(value)
new Date (year, month [, date [, hours [, minutes [, seconds [, ms ] ] ] ] ] )
new Date('9 August 2013');
new Date('9 Aug 2013');
new Date('9 Augu 2013');
new Date('9 Augustagfsdgsd 2013');
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
toTimeString() and toLocaleDateString()
/* 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(/%[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;
});
}
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"