Created
November 27, 2024 03:25
-
-
Save sorcerykid/229961e15a11279ec3b9df6ce1e3f380 to your computer and use it in GitHub Desktop.
Awk-compatible implementation of strftime() function 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
function strftime( tmpl, timestamp ) | |
{ | |
let regex = /%([admbyYzZHMS])/g; | |
let date = new Date( ( timestamp + 60 * getTimezone( ) ) * 1000 ); | |
let utc_format = date.toUTCString( ); // Tue, 12 May 2020 23:50:21 GMT | |
let iso_format = date.toISOString( ); // 2020-05-12T23:50:21.817Z | |
return tmpl.replace( regex, function ( exp, type ) | |
{ | |
if( exp == '%%' ) | |
return '%'; | |
switch( type ) { | |
case 'a': | |
return utc_format.substr( 0, 3 ); | |
case 'd': | |
return iso_format.substr( 8, 2 ); | |
case 'm': | |
return iso_format.substr( 5, 2 ); | |
case 'b': | |
return utc_format.substr( 8, 3 ); | |
case 'y': | |
return iso_format.substr( 2, 2 ); | |
case 'Y': | |
return iso_format.substr( 0, 4 ); | |
case 'H': | |
return iso_format.substr( 11, 2 ); | |
case 'M': | |
return iso_format.substr( 14, 2 ); | |
case 'S': | |
return iso_format.substr( 17, 2 ); | |
} | |
} ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment