Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active October 30, 2024 18:31
Show Gist options
  • Select an option

  • Save WebReflection/6076a40777b65c397b2b9b97247520f0 to your computer and use it in GitHub Desktop.

Select an option

Save WebReflection/6076a40777b65c397b2b9b97247520f0 to your computer and use it in GitHub Desktop.
// https://webreflection.medium.com/using-the-input-datetime-local-9503e7efdce
Date.prototype.toDatetimeLocal =
function toDatetimeLocal() {
var
date = this,
ten = function (i) {
return (i < 10 ? '0' : '') + i;
},
YYYY = date.getFullYear(),
MM = ten(date.getMonth() + 1),
DD = ten(date.getDate()),
HH = ten(date.getHours()),
II = ten(date.getMinutes()),
SS = ten(date.getSeconds())
;
return YYYY + '-' + MM + '-' + DD + 'T' +
HH + ':' + II + ':' + SS;
};
Date.prototype.fromDatetimeLocal = (function (BST) {
// BST should not be present as UTC time
return new Date(BST).toISOString().slice(0, 16) === BST ?
// if it is, it needs to be removed
function () {
return new Date(
this.getTime() +
(this.getTimezoneOffset() * 60000)
).toISOString();
} :
// otherwise can just be equivalent of toISOString
Date.prototype.toISOString;
}('2006-06-06T06:06'));
@WebReflection

Copy link
Copy Markdown
Author

it doesn't have to be a Date.prototype, it would just work as well as function toDatetimeLocal(date) ... but you've got the point.

@marchant

marchant commented May 9, 2017

Copy link
Copy Markdown

Don't apologize for a clean object-oriented proposal, this method belong on a Date instance, not an ugly "utility" function !

@john-doherty

Copy link
Copy Markdown

nice work!

@terary

terary commented Jan 18, 2019

Copy link
Copy Markdown

Thanks for your help

@osmanmesutozcan

Copy link
Copy Markdown

Thanks a lot. Saved my sanity

@valmirphp

Copy link
Copy Markdown

thanks!

@Olimarrex

Olimarrex commented Nov 10, 2022

Copy link
Copy Markdown

toDatetimeLocal won't work if you pass it a Date object with a year earlier than 1,000, since it won't pad the start with 0s.

@WebReflection

Copy link
Copy Markdown
Author

@Olimarrex I am not sure anyone needs that in 2022 but it's easy to solve too?

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