前端學習_10.Javascript Date對象

JavaScript Date對象

定義

  • Date 對象用於處理日期與時間。

創建

創建Date 對象: new Date()

  • 以下四種方法同樣可以創建 Date 對象:
    • var d = new Date();
    • var d = new Date(milliseconds);
    • var d = new Date(dateString);
    • var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

常用方法

方法 描述 輸出
toLocaleDateString() 根據本地時間格式,把 Date 對象的日期部分轉換爲字符串。 2018/10/15
toLocaleTimeString() 把 Date 對象的時間部分轉換爲字符串。 上午9:27:51
toLocaleString() 據本地時間格式,把 Date 對象轉換爲字符串。 2018/10/15 上午9:27:51
toUTCString() 根據世界時,把 Date 對象轉換爲字符串。 Mon, 15 Oct 2018 01:27:51 GMT
toDateString() 把 Date 對象的日期部分轉換爲字符串。 Mon Oct 15 2018
toTimeString() 把 Date 對象的時間部分轉換爲字符串。 09:27:51 GMT+0800 (中國標準時間)
toString() 把 Date 對象轉換爲字符串。 Mon Oct 15 2018 09:27:51 GMT+0800 (中國標準時間)
getTime() 返回 1970 年 1 月 1 日至今的毫秒數。 1539566871103
parse() 返回1970年1月1日午夜到指定日期(字符串)的毫秒數。 1539566871103

推薦moment

JavaScript 日期處理類庫

下載安裝

  • bower install moment --save # bower
  • npm install moment --save # npm

日期格式化

實例 輸出
moment().format(‘MMMM Do YYYY, h:mm:ss a’); 十月 15日 2018, 9:42:20 上午
moment().format(‘dddd’); 星期一
moment().format(“MMM Do YY”); 10月 15日 18
moment().format(‘YYYY [escaped] YYYY’); 2018 escaped 2018
moment().format(); 2018-10-15T09:42:20+08:00

中文支持

引入Moment.js中文字典部分

<script src="../bower_components/moment/moment.js" ></script>
		
<script src="../bower_components/moment/locale/zh-cn.js" ></script>

可以在zh-cn.js腳本文件中,修改自定義的日期格式

	...
    var zhCn = moment.defineLocale('zh-cn', {
        months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
        monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
        weekdays : '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
        weekdaysShort : '週日_週一_週二_週三_週四_週五_週六'.split('_'),
        weekdaysMin : '日_一_二_三_四_五_六'.split('_'),
        longDateFormat : {
            LT : 'HH:mm',
            LTS : 'HH:mm:ss',
            L : 'YYYY-MM-DD',
            LL : 'YYYY年M月D日',
            LLL : 'YYYY年M月D日Ah點mm分',
            LLLL : 'YYYY年M月D日ddddAh點mm分',
            l : 'YYYY-M-D',
            ll : 'YYYY年M月D日',
            lll : 'YYYY年M月D日 HH:mm',
            llll : 'YYYY年M月D日dddd HH:mm'
        },
        ...
實例 輸出
moment().format(‘L’); 2018-10-15
moment().format(‘l’); 2018-10-15
moment().format(‘LL’); 2018年10月15日
moment().format(‘ll’); 2018年10月15日
moment().format(‘LLL’); 2018年10月15日上午9點45分
moment().format(‘lll’); 2018年10月15日上午9點45分
moment().format(‘LLLL’); 2018年10月15日星期一上午9點45分
moment().format(‘llll’); 2018年10月15日星期一上午9點45分
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章