时间格式化插件jquery-dateFormat

做项目难免遇上格式化时间,而且可能不是每个地方都显示成一个样子,所以服务器端做这个不太方便。

jquery-dateFormat

Format patterns

  • Date and time patterns

  • yy = short year

  • yyyy = long year

  • M = month (1-12)

  • MM = month (01-12)

  • MMM = month abbreviation (Jan, Feb … Dec)

  • MMMM = long month (January, February … December)

  • d = day (1 - 31)

  • dd = day (01 - 31)

  • ddd = day of the week in words (Monday, Tuesday … Sunday)

  • D - Ordinal day (1st, 2nd, 3rd, 21st, 22nd, 23rd, 31st, 4th…)

  • h = hour in am/pm (0-12)

  • hh = hour in am/pm (00-12)

  • H = hour in day (0-23)

  • HH = hour in day (00-23)

  • mm = minute

  • ss = second

  • SSS = milliseconds

  • a = AM/PM marker

  • p = a.m./p.m. marker

支持的时间格式

  • 2009-12-18 10:54:50.546 (default java.util.Date.toString output)

  • Wed Jan 13 10:43:41 CET 2010 (???)

  • 2010-10-19T11:40:33.527+02:00 (default JAXB formatting of java.util.Date)

  • Sat Mar 05 2011 11:47:35 GMT-0300 (BRT) (default JavaScript new Date().toString() output)

  • Unix Timestamp (e.g. new Date().getTime())

例子

使用css来格式化

<span class="shortDateFormat">2009-12-18 10:54:50.546</span>
<span class="longDateFormat">2009-12-18 10:54:50.546</span>

默认的shortDateFormat 和 longDateFormat 这样来定义:

jQuery.format.date.defaultShortDateFormat = "dd/MM/yyyy";
jQuery.format.date.defaultLongDateFormat = "dd/MM/yyyy HH:mm:ss";

输出

#1 18/12/2009
#2 18/12/2009 10:54:50

用javascript来格式化

1
2
3
4
<script>
      document.write($.format.date("2009-12-18 10:54:50.546", "Test: dd/MM/yyyy"));
      document.write($.format.date("Wed Jan 13 10:43:41 CET 2010", "dd~MM~yyyy"));
</script>

输出

#1 Test: 18/12/2009
#2 18~12~2009