使用 Javascript 格式化当前时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14638018/
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
Current time formatting with Javascript
提问by Seong Lee
I want to get current time in a specific format with javascript.
我想使用 javascript 以特定格式获取当前时间。
With the function below and calling it will give me Fri Feb 01 2013 13:56:40 GMT+1300 (New Zealand Daylight Time)but I want to format it like Friday 2:00pm 1 Feb 2013
使用下面的函数并调用它会给我 2013 年 2 月 1 日星期五 13:56:40 GMT+1300(新西兰夏令时),但我想将其格式化为 2013 年 2 月 1 日星期五下午 2:00
var d = new Date();
var x = document.getElementById("time");
x.innerHTML = d;
Of course, code above doesn't have any formatting logic but I have not come across with any "working" formatters yet.
当然,上面的代码没有任何格式化逻辑,但我还没有遇到任何“工作”格式化程序。
回答by Ye Lin Aung
You may want to try
你可能想尝试
var d = new Date();
d.toLocaleString(); // -> "2/1/2013 7:37:08 AM"
d.toLocaleDateString(); // -> "2/1/2013"
d.toLocaleTimeString(); // -> "7:38:05 AM"
回答by gilly3
A JavaScript Date has several methods allowing you to extract its parts:
JavaScript 日期有多种方法允许您提取其部分:
getFullYear()- Returns the 4-digit yeargetMonth()- Returns a zero-based integer (0-11) representing the month of the year.getDate()- Returns the day of the month (1-31).getDay()- Returns the day of the week (0-6). 0 is Sunday, 6 is Saturday.getHours()- Returns the hour of the day (0-23).getMinutes()- Returns the minute (0-59).getSeconds()- Returns the second (0-59).getMilliseconds()- Returns the milliseconds (0-999).getTimezoneOffset()- Returns the number of minutes between the machine local time and UTC.
getFullYear()- 返回 4 位年份getMonth()- 返回一个从零开始的整数 (0-11),表示一年中的月份。getDate()- 返回一个月中的第几天 (1-31)。getDay()- 返回星期几 (0-6)。0 是星期日,6 是星期六。getHours()- 返回一天中的小时 (0-23)。getMinutes()- 返回分钟 (0-59)。getSeconds()- 返回第二个 (0-59)。getMilliseconds()- 返回毫秒 (0-999)。getTimezoneOffset()- 返回机器本地时间和 UTC 之间的分钟数。
There are no built-in methods allowing you to get localized strings like "Friday", "February", or "PM". You have to code that yourself. To get the string you want, you at least need to store string representations of days and months:
没有内置方法允许您获取本地化字符串,例如“Friday”、“February”或“PM”。你必须自己编码。要获得您想要的字符串,您至少需要存储日期和月份的字符串表示形式:
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
Then, put it together using the methods above:
然后,使用上述方法将其组合在一起:
var d = new Date();
var day = days[d.getDay()];
var hr = d.getHours();
var min = d.getMinutes();
if (min < 10) {
min = "0" + min;
}
var ampm = "am";
if( hr > 12 ) {
hr -= 12;
ampm = "pm";
}
var date = d.getDate();
var month = months[d.getMonth()];
var year = d.getFullYear();
var x = document.getElementById("time");
x.innerHTML = day + " " + hr + ":" + min + ampm + " " + date + " " + month + " " + year;
I have a date format function I like to include in my standard library. It takes a format string parameter that defines the desired output. The format strings are looselybased on .Net custom Date and Time format strings. For the format you specified the following format string would work: "dddd h:mmtt d MMM yyyy".
我有一个我喜欢包含在我的标准库中的日期格式函数。它采用定义所需输出的格式字符串参数。格式字符串松散地基于.Net 自定义日期和时间格式字符串。对于您指定的格式,以下格式字符串将起作用: "dddd h:mmtt d MMM yyyy".
var d = new Date();
var x = document.getElementById("time");
x.innerHTML = formatDate(d, "dddd h:mmtt d MMM yyyy");
Demo:jsfiddle.net/BNkkB/1
Here is my full date formatting function:
这是我的完整日期格式化功能:
function formatDate(date, format, utc) {
var MMMM = ["\x00", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var MMM = ["\x01", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var dddd = ["\x02", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var ddd = ["\x03", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
function ii(i, len) {
var s = i + "";
len = len || 2;
while (s.length < len) s = "0" + s;
return s;
}
var y = utc ? date.getUTCFullYear() : date.getFullYear();
format = format.replace(/(^|[^\])yyyy+/g, "" + y);
format = format.replace(/(^|[^\])yy/g, "" + y.toString().substr(2, 2));
format = format.replace(/(^|[^\])y/g, "" + y);
var M = (utc ? date.getUTCMonth() : date.getMonth()) + 1;
format = format.replace(/(^|[^\])MMMM+/g, "" + MMMM[0]);
format = format.replace(/(^|[^\])MMM/g, "" + MMM[0]);
format = format.replace(/(^|[^\])MM/g, "" + ii(M));
format = format.replace(/(^|[^\])M/g, "" + M);
var d = utc ? date.getUTCDate() : date.getDate();
format = format.replace(/(^|[^\])dddd+/g, "" + dddd[0]);
format = format.replace(/(^|[^\])ddd/g, "" + ddd[0]);
format = format.replace(/(^|[^\])dd/g, "" + ii(d));
format = format.replace(/(^|[^\])d/g, "" + d);
var H = utc ? date.getUTCHours() : date.getHours();
format = format.replace(/(^|[^\])HH+/g, "" + ii(H));
format = format.replace(/(^|[^\])H/g, "" + H);
var h = H > 12 ? H - 12 : H == 0 ? 12 : H;
format = format.replace(/(^|[^\])hh+/g, "" + ii(h));
format = format.replace(/(^|[^\])h/g, "" + h);
var m = utc ? date.getUTCMinutes() : date.getMinutes();
format = format.replace(/(^|[^\])mm+/g, "" + ii(m));
format = format.replace(/(^|[^\])m/g, "" + m);
var s = utc ? date.getUTCSeconds() : date.getSeconds();
format = format.replace(/(^|[^\])ss+/g, "" + ii(s));
format = format.replace(/(^|[^\])s/g, "" + s);
var f = utc ? date.getUTCMilliseconds() : date.getMilliseconds();
format = format.replace(/(^|[^\])fff+/g, "" + ii(f, 3));
f = Math.round(f / 10);
format = format.replace(/(^|[^\])ff/g, "" + ii(f));
f = Math.round(f / 10);
format = format.replace(/(^|[^\])f/g, "" + f);
var T = H < 12 ? "AM" : "PM";
format = format.replace(/(^|[^\])TT+/g, "" + T);
format = format.replace(/(^|[^\])T/g, "" + T.charAt(0));
var t = T.toLowerCase();
format = format.replace(/(^|[^\])tt+/g, "" + t);
format = format.replace(/(^|[^\])t/g, "" + t.charAt(0));
var tz = -date.getTimezoneOffset();
var K = utc || !tz ? "Z" : tz > 0 ? "+" : "-";
if (!utc) {
tz = Math.abs(tz);
var tzHrs = Math.floor(tz / 60);
var tzMin = tz % 60;
K += ii(tzHrs) + ":" + ii(tzMin);
}
format = format.replace(/(^|[^\])K/g, "" + K);
var day = (utc ? date.getUTCDay() : date.getDay()) + 1;
format = format.replace(new RegExp(dddd[0], "g"), dddd[day]);
format = format.replace(new RegExp(ddd[0], "g"), ddd[day]);
format = format.replace(new RegExp(MMMM[0], "g"), MMMM[M]);
format = format.replace(new RegExp(MMM[0], "g"), MMM[M]);
format = format.replace(/\(.)/g, "");
return format;
};
回答by Joomler
2017 update: use toLocaleDateStringand toLocaleTimeStringto format dates and times. The first parameter passed to these methods is a locale value, such as en-us. The second parameter, where present, specifies formatting options, such as the long form for the weekday.
2017 更新:使用toLocaleDateString和toLocaleTimeString来格式化日期和时间。传递给这些方法的第一个参数是区域设置值,例如en-us。第二个参数(如果存在)指定格式选项,例如工作日的长格式。
let date = new Date();
let options = {
weekday: "long", year: "numeric", month: "short",
day: "numeric", hour: "2-digit", minute: "2-digit"
};
console.log(date.toLocaleTimeString("en-us", options));
Output : Wednesday, Oct 25, 2017, 8:19 PM
输出:2017 年 10 月 25 日,星期三,晚上 8:19
Please refer below link for more details.
请参阅以下链接了解更多详情。
回答by thdoan
You can use my port of strftime:
您可以使用我的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 || 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 "Thursday 4:45pm 15 Sep 2016"
strftime('%A %l:%M%P %e %b %Y');
// You can optionally pass it a Date object
// Returns "Friday 2:00pm 1 Feb 2013"
strftime('%A %l:%M%P %e %b %Y', new Date('Feb 1, 2013 2:00 PM'));
The latest code is available here: https://github.com/thdoan/strftime
最新代码可在此处获得:https: //github.com/thdoan/strftime
回答by Lee Meador
Look at the internals of the Date class and you will see that you can extract all the bits (date, month, year, hour, etc).
查看 Date 类的内部结构,您将看到您可以提取所有位(日期、月份、年份、小时等)。
http://www.w3schools.com/jsref/jsref_obj_date.asp
http://www.w3schools.com/jsref/jsref_obj_date.asp
For something like Fri 23:00 1 Feb 2013the code is like:
对于类似Fri 23:00 1 Feb 2013的代码是这样的:
date = new Date();
weekdayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var dateString = weekdayNames[date.getDay()] + " "
+ date.getHours() + ":" + ("00" + date.getMinutes()).slice(-2) + " "
+ date.getDate() + " " + monthNames[date.getMonth()] + " " + date.getFullYear();
console.log(dateString);
**** Modified 2019-05-29 to keep 3 downvoters happy
**** 修改 2019-05-29 以保持 3 位反对者高兴
回答by slf
There are many great libraries out there, for those interested
有很多很棒的图书馆,感兴趣的人
There really shouldn't be a need these days to invent your own formatting specifiers.
这些天真的不需要发明自己的格式说明符。
回答by Ronnie Royston
2.39KB minified. One file. https://github.com/rhroyston/clock-js
2.39KB 缩小。一档。https://github.com/rhroyston/clock-js
Current Time is
当前时间是
var str = clock.month;
var m = str.charAt(0).toUpperCase() + str.slice(1,3); //gets you abbreviated month
clock.weekday + ' ' + clock.time + ' ' + clock.day + ' ' + m + ' ' + clock.year; //"tuesday 5:50 PM 3 May 2016"
回答by Cris
d = Date.now();
d = new Date(d);
d = (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear()+' '+(d.getHours() > 12 ? d.getHours() - 12 : d.getHours())+':'+d.getMinutes()+' '+(d.getHours() >= 12 ? "PM" : "AM");
console.log(d);
回答by Wael Chorfan
ISO8601 (eg: HH:MM:SS , 07:55:55 , or 18:50:30) on chrome :
ISO8601(例如: HH:MM:SS 、 07:55:55 或 18:50:30 )铬:
new Date(Date.now()).toTimeString().substr(0,8);
新日期(Date.now()).toTimeString().substr(0,8);
on edge :
边缘 :
new Date(Date.now()).toLocaleTimeString();
新日期(Date.now()).toLocaleTimeString();
回答by Simon
function formatTime(date){
d = new Date(date);
var h=d.getHours(),m=d.getMinutes(),l="AM";
if(h > 12){
h = h - 12;
}
if(h < 10){
h = '0'+h;
}
if(m < 10){
m = '0'+m;
}
if(d.getHours() >= 12){
l="PM"
}else{
l="AM"
}
return h+':'+m+' '+l;
}
Usage & result:
用法和结果:
var formattedTime=formatTime(new Date('2020 15:00'));
// Output: "03:00 PM"

