2
\$\begingroup\$

I just coded this formatter to format timestamps in javascript (I tied it to underscore for convenience), any remark?

_.toDate = function(epoch, format, locale) { 
 var date = new Date(epoch),
 format = format || 'dd/mm/YY',
 locale = locale || 'en'
 dow = {};
 dow.en = [
 'Sunday',
 'Monday',
 'Tuesday',
 'Wednesday',
 'Thursday',
 'Friday',
 'Saturday'
 ];
 var formatted = format
 .replace('D', dow[locale][date.getDay()])
 .replace('dd', ("0" + date.getDate()).slice(-2))
 .replace('mm', ("0" + (date.getMonth() + 1)).slice(-2))
 .replace('yyyy', date.getFullYear())
 .replace('yy', (''+date.getFullYear()).slice(-2))
 .replace('hh', date.getHours())
 .replace('mn', date.getMinutes());
 return formatted;
}

usage

_.toDate($.now(), "dd-mm-yy at hh:mn");
// Will output:
"27-03-13 at 17:20"
Quill
12k5 gold badges41 silver badges93 bronze badges
asked Mar 27, 2013 at 17:21
\$\endgroup\$
1
  • 2
    \$\begingroup\$ I like it (except that I'll stick to some commonly used format, for instance the one php uses) \$\endgroup\$ Commented Mar 27, 2013 at 22:34

2 Answers 2

1
\$\begingroup\$

I would use a library that is designed for this, such as Moment.js. It is a lot more flexible, and has internationalization support also.

answered Apr 1, 2013 at 19:17
\$\endgroup\$
0
\$\begingroup\$

What happens when you add the Hungarian locale

dow.hu = [
 'vasárnap',
 'hétfő',
 'kedd',
 'szerda',
 'csütörtök',
 'péntek',
 'szombat'
]

and try to format

_.toDate(new Date(2013, 07, 30, 12, 0, 0, 0), 'D dd mm, yy', 'hu');

?

answered Jul 31, 2013 at 17:09
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.