格式化Date和分析格式化Date字符串的JS代码


最近打算重构DateChooser控件,使用ASP.NET2.0新特性,不使用HTC以更好支持Cross-browser,先写了个日期格式的JS文件,欢迎大家使用

//Date.js
Date.prototype.format = function(formatter)
{
  if(!formatter || formatter == "")
  {
    formatter = "yyyy-MM-dd";
  }
  var year = this.getYear().toString();
  var month = (this.getMonth() + 1).toString();
  var day = this.getDate().toString();
  var yearMarker = formatter.replace(/[^y|Y]/g,'');
  if(yearMarker.length == 2)
  {
    year = year.substring(2,4);
  }  
  var monthMarker = formatter.replace(/[^m|M]/g,'');
  if(monthMarker.length > 1)
  {
    if(month.length == 1)
    {
      month = "0" + month;
    }
  }  
  var dayMarker = formatter.replace(/[^d]/g,'');
  if(dayMarker.length > 1)
  {
    if(day.length == 1)
    {
      day = "0" + day;
    }
  }  
  return formatter.replace(yearMarker,year).replace(monthMarker,month).replace(dayMarker,day);  
}
  
Date.parseString = function(dateString,formatter)
{
  var today = new Date();
  if(!dateString || dateString == "")
  {
    return today;
  }
  if(!formatter || formatter == "")
  {
    formatter = "yyyy-MM-dd";
  } 
  var yearMarker = formatter.replace(/[^y|Y]/g,''); 
  var monthMarker = formatter.replace(/[^m|M]/g,''); 
  var dayMarker = formatter.replace(/[^d]/g,'');
  var yearPosition = formatter.indexOf(yearMarker);
  var yearLength = yearMarker.length;
  var year = dateString.substring(yearPosition ,yearPosition + yearLength) * 1;
  if( yearLength == 2)
  {
    if(year < 50 )
    {
      year += 2000;
    }
    else
    {
      year += 1900;
    }
  }
  var monthPosition = formatter.indexOf(monthMarker);
  var month = dateString.substring(monthPosition,monthPosition + monthMarker.length) * 1 - 1;
  var dayPosition = formatter.indexOf(dayMarker);
  var day = dateString.substring( dayPosition,dayPosition + dayMarker.length )* 1;
  return new Date(year,month,day);
}

  使用方法(只支持日期部分,当然要先引用<script src="THIN/ClientFiles/Date.js" type="text/javascript"></script>):

alert(Date.parseString(new Date().format("MM月dd日yy年"),"MM月dd日yy年"));
var today = new Date();
var todayString = today.format("yyyy-MM-dd");
alert(todayString);
var parsedDate = Date.parseString(todayString);
alert(parsedDate);

  Birdshome写过URL的工具类,忘了有没有写Date的了



相关阅读:
图片展示效果 鼠标经过变大图,支持FF
DB2未来版“Viper 2” ——为IT敏捷加速
JavaScript 题型问答有答案参考
php下intval()和(int)转换使用与区别
网页制作中的水平居中和垂直居中解决方法集合
oracle10g 控制台启动端口修改
ASP.NET Routing对请求的处理方式
Dreamweaver中预览PHP和ASP
基于mysql的论坛(7)
SQLPLUS命令的使用大全
CSS教程:简单理解em
php数组函数序列之array_combine() - 数组合并函数使用说明
使用ASP在IIS创建WEB站点的函数
Discuz!安装提示“include_path='.;c:\php5\pear'”错误的解决方法
快速导航

Copyright © 2016 phpStudy |