欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

javascript转换日期字符串为Date对象

程序员文章站 2022-03-30 22:30:57
...
日期格式:2011-08-30 12:49:50
---------------------------------------------------
第一种实现方式
var strArray = str.split(" ");
var strDate = strArray[0].split("-");
var strTime = strArray[1].split(":");
var date = new Date(strDate[0],(strDate[1]-praseInt(1)),strDate(2),strTime(0),strTime(1),strTime(2));


----------------------------------------------------------
第二种方式:
var date = new Date(Date.parse(str.replace(/-/g, "/");



-------------------------------------------------------------
测试代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
	<script src = "js/jquery-1.6.2.min.js" type="text/javascript"></script>
	<script src = "datePicker/WdatePicker.js" type="text/javascript"></script>
	<script type="text/javascript">
		$(document).ready(function(){
			
			$('#btn_time').click(function(){
				var startDate = $('#startDate').val();	
				var endDate = $('#endDate').val();
				
				var start_date = new Date(Date.parse(startDate.replace(/-/ig, "/")));
				var end_date = new Date(Date.parse(endDate.replace(/-/ig, "/")));
				alert(start_date);
				if(end_date < start_date){
					alert("开始时间必须大于结束时间!");
					$('#startDate').attr("value","");
					$('#endDate').attr("value","");
					return;
				}
				var startYear = start_date.getYear();
				var startMonth = start_date.getMonth()+1;
				var startHour = start_date.getHours();
				
				var endYear = end_date.getYear();
				var endMonth = end_date.getMonth()+1;
				var endHour = end_date.getHours();
				
				if(startYear == endYear){
					//do something
				}
				
			});	
		
			
	});
	
	</script>
	
</head>
<body>
	开始时间:<input id="startDate" name="startDate" class="Wdate" onclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm'});"/>
	<br/>
	结束时间:<input id="endDate" name="endDate" class="Wdate" onclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm'});"/>
	<input type="text" id="text" name="text" value="" />
	<input type="button" id="btn_time" value="时间测试" />
</body>
</html>