Last active
December 16, 2015 08:59
-
-
Save physacco/5409925 to your computer and use it in GitHub Desktop.
Parse and format time in JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Parse and format time. | |
// Written by physacco. 2011-05-13. | |
// | |
// Tested on: | |
// - Mozilla SpiderMonkey JavaScript-C 1.7.0 2007-10-03. | |
// - Mozilla Rhino 1.7 release 0.7.r2.fc12 2009 07 28. | |
// | |
// To run it with nodejs, substitute print with console.log. | |
// YYYY-mm-dd HH:MM:SS | |
function parseUTCDate(str) { | |
var re = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/; | |
var md = re.exec(str); | |
if(md) { | |
var year = parseInt(md[1]); | |
var month = parseInt(md[2]) - 1; | |
var date = parseInt(md[3]); | |
var hour = parseInt(md[4]); | |
var minute = parseInt(md[5]); | |
var second = parseInt(md[6]); | |
var dt = new Date(); | |
dt.setUTCFullYear(year); | |
dt.setUTCMonth(month); | |
dt.setUTCDate(date); | |
dt.setUTCHours(hour); | |
dt.setUTCMinutes(minute); | |
dt.setUTCSeconds(second); | |
return dt; | |
} | |
else { | |
return null; | |
} | |
} | |
// dateobj: a Date object | |
function formatDateLocale(dateobj) { | |
var year = dateobj.getFullYear(); | |
var month = dateobj.getMonth() + 1; | |
var date = dateobj.getDate(); | |
var hour = dateobj.getHours(); | |
var minute = dateobj.getMinutes(); | |
var second = dateobj.getSeconds(); | |
var YY = year; | |
var mm = month < 10 ? '0' + month : month; | |
var dd = date < 10 ? '0' + date : date; | |
var HH = hour < 10 ? '0' + hour : hour; | |
var MM = minute < 10 ? '0' + minute : minute; | |
var SS = second < 10 ? '0' + second : second; | |
return YY+'-'+mm+'-'+dd+' '+HH+':'+MM+':'+SS; | |
} | |
var utc_str = "2011-05-13 13:56:34"; | |
var date = parseUTCDate(utc_str); | |
print(date); // or console.log on nodejs | |
var locale_str = formatDateLocale(date); | |
print(locale_str); // or console.log on nodejs | |
// Output: | |
// Fri May 13 2011 21:56:34 GMT+0800 (CST) | |
// 2011-05-13 21:56:34 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment