使用Javascript当前时间格式
我想用javascript来获取特定格式的当前时间。
使用下面的函数将会给我Fri Feb 01 2013 13:56:40 GMT + 1300(新西兰夏令时间),但我想格式化它像星期五下午2:00下午2013年2月1日
var d = new Date(); var x = document.getElementById("time"); x.innerHTML = d;
当然,上面的代码没有任何格式化逻辑,但我还没有遇到任何“工作”的格式化器。
JavaScriptdate有几种方法允许您提取其部分:
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之间的分钟数。
没有内置方法允许您获取本地化的string,如“星期五”,“二月”或“PM”。 你必须自己编码。 为了得到你想要的string,你至less需要存储几天和几个月的string表示forms:
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
然后,使用上面的方法把它们放在一起:
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;
我有一个date格式函数,我喜欢包括在我的标准库。 它需要一个格式string参数来定义所需的输出。 格式string松散地基于.Net自定义date和时间格式string 。 对于您指定的格式,以下格式string可以工作: "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");
演示: jsfiddle.net/BNkkB/1
这是我的完整date格式化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, "$1" + y); format = format.replace(/(^|[^\\])yy/g, "$1" + y.toString().substr(2, 2)); format = format.replace(/(^|[^\\])y/g, "$1" + y); var M = (utc ? date.getUTCMonth() : date.getMonth()) + 1; format = format.replace(/(^|[^\\])MMMM+/g, "$1" + MMMM[0]); format = format.replace(/(^|[^\\])MMM/g, "$1" + MMM[0]); format = format.replace(/(^|[^\\])MM/g, "$1" + ii(M)); format = format.replace(/(^|[^\\])M/g, "$1" + M); var d = utc ? date.getUTCDate() : date.getDate(); format = format.replace(/(^|[^\\])dddd+/g, "$1" + dddd[0]); format = format.replace(/(^|[^\\])ddd/g, "$1" + ddd[0]); format = format.replace(/(^|[^\\])dd/g, "$1" + ii(d)); format = format.replace(/(^|[^\\])d/g, "$1" + d); var H = utc ? date.getUTCHours() : date.getHours(); format = format.replace(/(^|[^\\])HH+/g, "$1" + ii(H)); format = format.replace(/(^|[^\\])H/g, "$1" + H); var h = H > 12 ? H - 12 : H == 0 ? 12 : H; format = format.replace(/(^|[^\\])hh+/g, "$1" + ii(h)); format = format.replace(/(^|[^\\])h/g, "$1" + h); var m = utc ? date.getUTCMinutes() : date.getMinutes(); format = format.replace(/(^|[^\\])mm+/g, "$1" + ii(m)); format = format.replace(/(^|[^\\])m/g, "$1" + m); var s = utc ? date.getUTCSeconds() : date.getSeconds(); format = format.replace(/(^|[^\\])ss+/g, "$1" + ii(s)); format = format.replace(/(^|[^\\])s/g, "$1" + s); var f = utc ? date.getUTCMilliseconds() : date.getMilliseconds(); format = format.replace(/(^|[^\\])fff+/g, "$1" + ii(f, 3)); f = Math.round(f / 10); format = format.replace(/(^|[^\\])ff/g, "$1" + ii(f)); f = Math.round(f / 10); format = format.replace(/(^|[^\\])f/g, "$1" + f); var T = H < 12 ? "AM" : "PM"; format = format.replace(/(^|[^\\])TT+/g, "$1" + T); format = format.replace(/(^|[^\\])T/g, "$1" + T.charAt(0)); var t = T.toLowerCase(); format = format.replace(/(^|[^\\])tt+/g, "$1" + t); format = format.replace(/(^|[^\\])t/g, "$1" + 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, "$1" + 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, "$1"); return format; };
你可能想尝试
d = new Date(); d.toLocaleString(); // -> "2/1/2013 7:37:08 AM" d.toLocaleDateString(); // -> "2/1/2013" d.toLocaleTimeString(); // -> "7:38:05 AM"
你可以使用我的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(/%[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; }); }
示例用法:
// 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'));
最新的代码可以在这里find: https : //github.com/thdoan/strftime
看看Date类的内部,你会看到你可以提取所有的位(date,月份,年份,小时等)。
http://www.w3schools.com/jsref/jsref_obj_date.asp
对于类似于Friday 2:00pm 1 Feb 2013
的代码,有点像:
var dateString = date.getDay() + " " + date.getHours() + ":" + date.getMinutes() ...
那里有很多很棒的图书馆,对那些感兴趣的人来说
现在真的不需要创build自己的格式化说明符。
2.39KB缩小。 一个文件。 https://github.com/rhroyston/clock-js
当前时间是
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"
要使用基本的Date类,你可以看看MDN的方法(而不是W3Schools由于这个原因 )。 在这里你可以find关于访问每个单一date/时间组件的相关方法的一个很好的描述,以及关于一个方法是否被弃用的信息。
否则,你可以看Moment.js这是一个很好的库用于date和时间处理。 你可以使用它来操纵date和时间(如parsing,格式化,国际化等)。
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);
对于时间我主要使用toLocaleDateString和toLocaleTimeString来格式化date和时间。 传递给这些方法的第一个参数是locale值,例如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));
function startTime() { var today = new Date(), h = checkTime(((today.getHours() + 11) % 12 + 1)), m = checkTime(today.getMinutes()), s = checkTime(today.getSeconds()); document.getElementById('demo').innerHTML = h + ":" + m + ":" + s; t = setTimeout(function () { startTime() }, 500); } startTime();
})();
5点12分○○秒
- 整整一分钟到最近的四分之一小时
- 如何在.net应用程序中使用SQL Server时间数据types?
- 如何以格式打印时间:2009-08-10 18:17:54.811
- 如何在Python中获取当前时间?
- as.POSIXct / as.POSIXlt和将字符向量转换为POSIXct / POSIXlt的strptime之间的区别
- 在Linux中测量时间 – 时间vs时钟vs getrusage vs clock_gettime vs gettimeofday vs timespec_get?
- 如何检查系统是12小时还是24小时?
- 在Python中使用%f与strftime()来获得微秒
- 如何recursion查找和列出目录中的最新修改的文件与子目录和时间?