JS 将Date对象和字符串转换成日期类型

来源:互联网 发布:上海黄金交易所软件下载 编辑:程序博客网 时间:2024/05/17 07:17

var date =new Date();  //该时间是获取用户的系统的时间

 alert(date); // 输出 :Thu Jun 28 11:09:52 UTC+0800 2012

 alert(date.toLocaleDateString());   //2102年6月28日

 alert(date.toLocaleTimeString());  //11:23:34

  alert(date.toLocaleString());    // 2102年6月28日 11:23:34

      var date = new Date();
      date.setFullYear("2014"); //set方法更改date对象的值 ,也可更改其他的如:年月日,时分秒.
      alert(date.toLocaleString( )  ); //输出: 2014年6月28日 12:00:14

 

将字符串形式的日期转换成日期对象

var strTime="2011-04-16"; //字符串日期格式  (年/月/日)        
var date= new Date(Date.parse(strTime.replace(/-/g,   "/"))); //js只识别带/的分隔符,转换成Data();

var month=date.getMonth()+1; //获取当前月份

  alert(date.toLocaleString()); //不同浏览器格式有差别:ff: 2011年4月16日 0:00:00   没有设置时间默认为0

    var strTime="2011-04-16 11:23:34"; //字符串日期格式  年/月/日 时:分:秒         
     var date= new Date(Date.parse(strTime.replace(/-/g,   "/"))); //js只识别带/的分隔符,转换成Data();
     var month=date.getMonth()+1; //获取当前月份
     alert(date.toLocaleString());  //不同浏览器有差别;ff:2011年4月16日 11:23:34

------------------------------------------------------------------------------------------------------

date.getYear()       //获取当前年份(2位)如:2012显示 112   ,不知为什么?
date.getFullYear()   //获取完整的年份(4位,1970-????) 如:2012
date.getMonth()     //获取当前月份(0-11,0代表1月)
date.getDate()       //获取当前日(1-31)
date.getDay()       //获取当前星期X(0-6,0代表星期天)
date.getTime()       //获取当前时间(从1970.1.1开始的毫秒数)
date.getHours()    //获取当前小时数(0-23)
date.getMinutes()    //获取当前分钟数(0-59)
date.getSeconds()     //获取当前秒数(0-59)
date.getMilliseconds()   //获取当前毫秒数(0-999)
date.toLocaleDateString()    //获取当前日期,如:2102年6月28日
date.toLocaleTimeString()   //获取当前时间,如:11:23:34
date.toLocaleString( )       //获取日期与时间,如: 2102年6月28日 11:23:34