JavaScript中日期时间操作

淩亂°似流年 2022-09-21 13:10 290阅读 0赞

1、JS 日期时间格式化

  1. Date.prototype.format = function(fmt) {
  2. var o = {
  3. "y+": this.getFullYear(),
  4. "M+": this.getMonth() + 1,
  5. "d+": this.getDate(),
  6. "H+": this.getHours(),
  7. "m+": this.getMinutes(),
  8. "s+": this.getSeconds(),
  9. "S": this.getMilliseconds(),
  10. "h+": (this.getHours() % 12),
  11. "a": (this.getHours() / 12) <= 1 ? "AM": "PM"
  12. };
  13. if (/(y+)/.test(fmt)) {
  14. fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  15. }
  16. for (var k in o) {
  17. if (new RegExp("(" + k + ")").test(fmt)) {
  18. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  19. }
  20. }
  21. return fmt;
  22. }

使用方式:

  1. new Date().format("yyyy-MM-dd HH:mm:ss"); // 2016-06-20 14:51:53
  2. new Date().format("yyyy-MM-dd hh:mm:ss"); // 2016-06-20 02:51:53
  3. new Date().format("yyyy-MM-dd HH:mm:ss S"); // 2016-06-20 14:51:53 56
  4. new Date().format("yyyy-MM-dd HH:mm:ss S a"); // 2016-06-20 14:51:53 56 PM
  5. new Date().format("yyyy年MM月dd日 HH时mm分ss秒"); // 2016年06月20日 14时51分53秒
  6. new Date().format("y-M-d H:m:s"); // 2016-06-20 14:51:53
  7. new Date().format("y-M-d H:m:s S"); // 2016-06-20 02:51:53 56

2、JS 日期时间格式校验

格式为:yyyy-MM-dd HH:mm:ss

  1. var checkDateTime = function (str){
  2. var reg = /^(\d{4})-(\d{1,2})-(\d{1,2})\s(\d{1,2}):(\d{1,2}):(\d{1,2})$/;
  3. var r = str.match(reg);
  4. if(r==null) return false;
  5. r[2]=r[2]-1;
  6. var d= new Date(r[1],r[2],r[3],r[4],r[5],r[6]);
  7. if(d.getFullYear()!=r[1]) return false;
  8. if(d.getMonth()!=r[2]) return false;
  9. if(d.getDate()!=r[3]) return false;
  10. if(d.getHours()!=r[4]) return false;
  11. if(d.getMinutes()!=r[5]) return false;
  12. if(d.getSeconds()!=r[6]) return false;
  13. return true;
  14. }

发表评论

表情:
评论列表 (有 0 条评论,290人围观)

还没有评论,来说两句吧...

相关阅读