打造自己的js库(date篇)

本文介绍了一个简单的JavaScript库,用于将日期格式化为常见的年-月-日或年/月/日等格式,并提供了具体实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

                                                  打造自己的js库(date篇)

项目中经常需要一些对时间进行格式化的需求,比如时间戳按指定格式转为"年-月-日"或者"年/月/日"的格式,这一篇就是提供一些类似new Date().Format这样的一些方法。

    namespace('gu.date');

    extend(gu.date,{
    /**
    *获取日期,默认日期为今天,默认分隔符为'-'
    * @param time
    * @returns {string}
    * @date 2017-11-21
    */
    toDateString:function (time) {
    var time = time ? time : new Date(),
    m = time.getMonth(),
    d = time.getDay(),
    y = time.getFullYear(),
    separator = arguments[1] ? arguments[1] : '-';

    return y + separator + (m.toString().length < 2 ? '0' + m : m) +separator +(d.toString().length < 2 ? '0' + d : d);
    },
    /**
    * 获取日期以及时间,默认日期为今天,默认分隔符为'-'
    * @param time
    * @returns {string}
    * @date 2017-11-21
    */
    toDateTimeString:function (time) {
    var time = time ? time : new Date(),
    h = time.getHours(),
    i = time.getMinutes(),
    s = time.getSeconds();

    return gu.date.toDateString.apply(this,arguments) + " " + (h.toString().length < 2 ? '0' + h : h)+ ":" + (i.toString().length < 2 ? '0' + i : i)+ ":" + (s.toString().length < 2 ? '0' + s : s);
    }
    });

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值