前端学习_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分
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值