javascript怎么将字符串转换为时间

2025-04-05 04:46:31
推荐回答(2个)
回答(1):

cript type="text/javascript">
//字符串转日期格式,strDate要转为日期格式的字符串
function getDate(strDate){
var date = eval('new Date(' + strDate.replace(/\d+(?=-[^-]+$)/,
function (a) { return parseInt(a, 10) - 1; }).match(/\d+/g) + ')');
return date;
}
//测试
alert(getDate("2035-05-09"));

回答(2):





字符串日期相互转换



        Date.prototype.format=function(pattern){
            var month=this.getMonth()+1
            ,date=this.getDate()
            ,hours=this.getHours()
            ,min=this.getMinutes()
            ,sec=this.getSeconds();
            return pattern.replace(/yyyy/g,this.getFullYear())
                        .replace(/yy/g,String(this.getFullYear()).substr(2,2))
                        .replace(/MM/g,month>=10?month:"0"+month)
                        .replace(/M\*/g,month)
                        .replace(/dd/g,date>=10?date:"0"+date)
                        .replace(/d\*/g,date)
                        .replace(/hh/gi,hours>=10?hours:"0"+hours)
                        .replace(/h\*/gi,hours)
                        .replace(/m\*/g,min)
                        .replace(/mm/g,min>=10?min:"0"+min)
                        .replace(/ss/g,sec>=10?sec:"0"+sec)
                        .replace(/s\*/g,sec);
        };
        
        String.prototype.toDate=function(){
            return new Date(this.replace(/-/g,"/"));
        };
    
        window.onload = function(){
            //日期转字符串
            var longMills = 1482291758773;
            var date = new Date(longMills);
            alert(date.format("yyyy-MM-dd HH:mm:ss"));
            //字符串转日期
            var str1 = "2016-12-21 15:12:32";
            var str2 = "2016/12/21 15:12:32";
            alert(str1.toDate());
            alert(str2.toDate());
            
        };


自定义插件处理.