Created
July 29, 2019 19:05
-
-
Save damiancipolat/8deb9966eaae1cc0139e7c3981cb6268 to your computer and use it in GitHub Desktop.
Get datetime with forma ISO 8601 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
const getTimeZone = ()=>{ | |
let timezone_offset_min = new Date().getTimezoneOffset(), | |
offset_hrs = parseInt(Math.abs(timezone_offset_min/60)), | |
offset_min = Math.abs(timezone_offset_min%60), | |
timezone_standard; | |
if(offset_hrs < 10) | |
offset_hrs = '0' + offset_hrs; | |
if(offset_min < 10) | |
offset_min = '0' + offset_min; | |
// Add an opposite sign to the offset | |
// If offset is 0, it means timezone is UTC | |
if(timezone_offset_min < 0) | |
timezone_standard = '+' + offset_hrs + ':' + offset_min; | |
else if(timezone_offset_min > 0) | |
timezone_standard = '-' + offset_hrs + ':' + offset_min; | |
else if(timezone_offset_min == 0) | |
timezone_standard = 'Z'; | |
return timezone_standard; | |
} | |
const datetime = ()=>{ | |
let dt = new Date(), | |
current_date = dt.getDate(), | |
current_month = dt.getMonth() + 1, | |
current_year = dt.getFullYear(), | |
current_hrs = dt.getHours(), | |
current_mins = dt.getMinutes(), | |
current_secs = dt.getSeconds(), | |
current_datetime; | |
// Add 0 before date, month, hrs, mins or secs if they are less than 0 | |
current_date = current_date < 10 ? '0' + current_date : current_date; | |
current_month = current_month < 10 ? '0' + current_month : current_month; | |
current_hrs = current_hrs < 10 ? '0' + current_hrs : current_hrs; | |
current_mins = current_mins < 10 ? '0' + current_mins : current_mins; | |
current_secs = current_secs < 10 ? '0' + current_secs : current_secs; | |
// Current datetime | |
// String such as 2016-07-16T19:20:30 | |
current_datetime = current_year + '-' + current_month + '-' + current_date + 'T' + current_hrs + ':' + current_mins + ':' + current_secs; | |
return current_datetime; | |
} | |
const iso8601 = ()=> datetime()+getTimeZone(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment