Skip to content

Instantly share code, notes, and snippets.

@noromanba
Last active August 1, 2020 03:13
Show Gist options
  • Save noromanba/6737784 to your computer and use it in GitHub Desktop.
Save noromanba/6737784 to your computer and use it in GitHub Desktop.
format current local date to "yyyy-MM-dd HH:mm:ss TZ-info" on X-browser
// X-browser print local datetime w/ yyyy-MM-dd HH:mm:ss TZInfo format
// e.g. 2014-11-20 03:16:26 GMT+0900 (JST)
// @author noromanba http://flavors.me/noromanba
// @license CC0 Univ PD http://creativecommons.org/publicdomain/zero/1.0
// c.f.
// https://gist.github.com/noromanba/6736822
// http://let.hatelabo.jp/noromanba/let/hJmcrJfO94ka/rev/hJmcruLM2p0H
// http://let.hatelabo.jp/noromanba/let/hJmcrJfO94ka
var toDateTimeTZInfoString = (function () {
// non-standard JS 1.6, Fx only; c.f.
// http://compatibility.shwups-cms.ch/en/home/?&&&property=Date.prototype.toLocaleFormat
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleFormat
if (Date.prototype.toLocaleFormat) {
return function () {
return new Date().toLocaleFormat('%Y-%m-%d %T %Z');
};
}
// Fx not supported yet; c.f.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
if (Date.prototype.toLocaleDateString) {
return function () {
var now = new Date();
return now.toLocaleDateString('ja', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).replace(/\//g, '-') + ' ' + now.toTimeString();
};
}
// Safari, almost browsers and mobile
return function () {
var now = new Date();
return [
now.getFullYear(),
'-', ('0' + (now.getMonth() + 1)).slice(-2),
'-', ('0' + now.getDate()).slice(-2),
' ', now.toTimeString()
].join('');
};
})();
@tomek-he-him
Copy link

How about new Date().toISOString().substr(0, 10)?

@noromanba
Copy link
Author

@tomekwi I want to put local time on this code. but toISOString() always TZ="Z" (UTC±0)

// run at 2014-11-20 02:+ (JST)
var now = new Date();
now.toISOString().substr(0, 10);
// "2014-11-19"
now.toISOString();
// "2014-11-19T17:30:34.015Z"
now.toString(); // same as `Date()`
// "Thu Nov 20 2014 02:30:34 GMT+0900 (JST)"

thx nice tips!

now.toISOString().substr(0, 10);

LGTM 👍
LGTM

@oshliaer
Copy link

oshliaer commented Mar 5, 2020

new Date().toLocaleDateString('fr-ca');
// $> 2020-03-05

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment