Last active
December 13, 2022 07:39
-
-
Save neilrackett/7881b5bef4cb4ae63af5c3a6a244cffa to your computer and use it in GitHub Desktop.
Convert PHP date string to Moment.js format
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 phpToMoment(str) { | |
let replacements = { | |
'd' : 'DD', | |
'D' : 'ddd', | |
'j' : 'D', | |
'l' : 'dddd', | |
'N' : 'E', | |
'S' : 'o', | |
'w' : 'e', | |
'z' : 'DDD', | |
'W' : 'W', | |
'F' : 'MMMM', | |
'm' : 'MM', | |
'M' : 'MMM', | |
'n' : 'M', | |
't' : '', // no equivalent | |
'L' : '', // no equivalent | |
'o' : 'YYYY', | |
'Y' : 'YYYY', | |
'y' : 'YY', | |
'a' : 'a', | |
'A' : 'A', | |
'B' : '', // no equivalent | |
'g' : 'h', | |
'G' : 'H', | |
'h' : 'hh', | |
'H' : 'HH', | |
'i' : 'mm', | |
's' : 'ss', | |
'u' : 'SSS', | |
'e' : 'zz', // deprecated since Moment.js 1.6.0 | |
'I' : '', // no equivalent | |
'O' : '', // no equivalent | |
'P' : '', // no equivalent | |
'T' : '', // no equivalent | |
'Z' : '', // no equivalent | |
'c' : '', // no equivalent | |
'r' : '', // no equivalent | |
'U' : 'X' | |
}; | |
return str.split('').map(chr => chr in replacements ? replacements[chr] : chr).join(''); | |
} | |
// Example | |
let formattedDate = moment().format(phpToMoment('D, Y-m-d H:i:s')); | |
console.log(formattedDate); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank God for you, this just saved me half an hour.