• ios的日期格式bug


       转眼又到了周末,转眼又要上班,转眼...大概这就是一眼万年的意思吧。

       这周继续IM(即时聊天),项目用的是LayIM移动端改装的,仅仅“借用”了一个聊天窗口。由于是内嵌App的页面,自然少不了Android和iOS的兼容问题,这次要谈的就是日期格式在iOS的bug。

      一般我们在页面渲染时间的时候都是xxxx-xx-xx,ios系统new Date(xxxx-xx-xx)的时候会报NaN-NaN-NaN NaN:NaN异常将xxxx-xx-xx的时间格式改为xxxx/xx/xx就可以解决这个问题。使用正则转换:

    /* 转换为时间戳 */
    function formatTimeStamp(date){
        return Date.parse(new Date(date)) || Date.parse(new Date(date.replace(/-/g,'/')));
    }
    formatTimeStamp('2017-11-11');

       JavaScript默认的时间格式我们一般情况下不会用,所以需要进行格式化,下面说说JavaScript时间格式化方法。

      很多时候,我们可以利用JavaScript中Date对象的内置方法来格式化,如:

    var d = new Date();
    console.log(d); // 输出:Mon Nov 04 2013 21:50:33 GMT+0800 (中国标准时间)
    console.log(d.toDateString()); // 日期字符串,输出:Mon Nov 04 2013
    console.log(d.toGMTString()); // 格林威治时间,输出:Mon, 04 Nov 2013 14:03:05 GMT
    console.log(d.toISOString()); // 国际标准组织(ISO)格式,输出:2013-11-04T14:03:05.420Z
    console.log(d.toJSON()); // 输出:2013-11-04T14:03:05.420Z
    console.log(d.toLocaleDateString()); // 转换为本地日期格式,视环境而定,输出:2013年11月4日
    console.log(d.toLocaleString()); // 转换为本地日期和时间格式,视环境而定,输出:2013年11月4日 下午10:03:05
    console.log(d.toLocaleTimeString()); // 转换为本地时间格式,视环境而定,输出:下午10:03:05
    console.log(d.toString()); // 转换为字符串,输出:Mon Nov 04 2013 22:03:05 GMT+0800 (中国标准时间)
    console.log(d.toTimeString()); // 转换为时间字符串,输出:22:03:05 GMT+0800 (中国标准时间)
    console.log(d.toUTCString()); // 转换为世界时间,输出:Mon, 04 Nov 2013 14:03:05 GMT

      

      如果上面的方法不能满足我们的要求,也可以自定义函数来格式化时间,如:

    // 对Date的扩展,将 Date 转化为指定格式的String
    // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
    // 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
    // 例子:
    // (new Date()).format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
    // (new Date()).format("yyyy-M-d h:m:s.S")   ==> 2006-7-2 8:9:4.18
    Date.prototype.format = function (fmt) { //author: meizz
    var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //
    "s+": this.getSeconds(), //
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
    }

      调用:

    // var date = 时间戳或者其他new Date能转换的格式
    new Date(date).format(“yyyy-MM-dd”); 

       

      更多扩展时间处理方法见:https://www.cnblogs.com/chenwenhao/p/10480234.html

  • 相关阅读:
    PHP
    linux文件分割(将大的日志文件分割成小的)
    centos安装ssdb
    SSDB 数据库如何换用 rocksdb 引擎?
    A PHP extension for Facebook's RocksDB
    看电影有感
    视频格式(转的豆瓣)
    7月7号项目讲解总结
    java注解Annotation
    xml的解析
  • 原文地址:https://www.cnblogs.com/chenwenhao/p/9462179.html
Copyright © 2020-2023  润新知