Skip to content

Instantly share code, notes, and snippets.

@neilrackett
Last active December 13, 2022 07:39
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neilrackett/7881b5bef4cb4ae63af5c3a6a244cffa to your computer and use it in GitHub Desktop.
Save neilrackett/7881b5bef4cb4ae63af5c3a6a244cffa to your computer and use it in GitHub Desktop.
Convert PHP date string to Moment.js format
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);
@ThatGuySam
Copy link

Thank God for you, this just saved me half an hour.

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