分享一個將指定日期格式的字串轉為日期的js函數toDate,jstodate

來源:互聯網
上載者:User

分享一個將指定日期格式的字串轉為日期的js函數toDate,jstodate

今天發現easyui的datetimebox不能正常顯示日期,接著自然就是實現toDate的功能,google了下,沒找到滿意的,都寫的很羅嗦。自己寫一個,本來以為js的正則也可以用命名group來弄,但是目前看javascript好像不支援。現在實現的代碼如下,希望對有需要的人也有協助。


//by dragonimp 2015.5.3//使用方法://"2015-5-5 9:10:10".toDate("yyyy-M-d hh:mm:ss")//"2015/5/5 9:10:10".toDate("yyyy/M/d hh:mm:ss")String.prototype.toDate = function (fmt) {    if (fmt == null) fmt = 'yyyy-MM-dd hh:mm:ss';    var str = this;    //fmt為日期格式,str為日期文字    var reg = /([yMdhmsS]+)/g;//日期格式中的字元    var key = {};    var tmpkeys = fmt.match(reg);    for (var i = 0 ; i < tmpkeys.length; i++) {        key[tmpkeys[i].substr(0, 1)] = i + 1;    }    var r = str.match(fmt.replace(reg, "(\\d+)"));    return new Date(r[key["y"]], r[key["M"]] - 1, r[key["d"]], r[key["h"]], r[key["m"]], r[key["s"]], r[key["S"]]);}

附:easyui的問題和解決方案。

問題:

<input  type="text" value="2015/5/6 23:00:00" id="xxxx" class="easyui-datetimebox" />
這個顯示出來的控制項,日期的“日”部分顯示不正確,會顯示當天的日期。

檢查了下,easyui已經引用了中文的資源檔,看了下資源檔,應該只支援"-"分割的日期,我這裡是"/"

解決:需要自己實現formatter和parser。

1.加上options

<input  type="text" value="2015/5/6 23:00:00" id="xxxx" class="easyui-datetimebox" data-options="formatter:datetimebox_format,parser:datetimebox_parse" />

2.實現解析和格式化函數

function datetimebox_format(date) {return date.toFormatString("yyyy/M/d h:mm:ss");}function datetimebox_parse(s) {  return s.toDate("yyyy/M/d hh:mm:ss");  }  //a)轉日期的,見前面我的toDate//b)下面轉字串的,來自網上Date.prototype.toFormatString = function (fmt) {    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;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.