Converting a string to a date in JavaScript
如何在JavaScript中将字符串转换为日期?
1 2 3 4 | var st ="date in some format" var dt = new date(); var dt_st= //st in date format same as dt |
字符串解析的最佳字符串格式是日期ISO格式以及JavaScript Date对象构造函数。
ISO格式的示例:
可是等等!仅使用"ISO格式"本身并不可靠。字符串有时被解析为UTC,有时也被解析为本地时间(基于浏览器供应商和版本)。最佳做法应始终是将日期存储为UTC并将计算作为UTC进行计算。
要将日期解析为UTC,请附加Z - 例如:
要以UTC显示日期,请使用
要在用户的本地时间显示日期,请使用
有关MDN |的更多信息日期和这个答案。
对于旧的Internet Explorer兼容性(小于9的IE版本在Date构造函数中不支持ISO格式),您应该将日期时间字符串表示形式拆分为它的部分,然后您可以使用构造函数使用日期时间部分,例如:
替代方法 - 使用适当的库:
您还可以利用Moment.js库,它允许使用指定的时区解析日期。
不幸的是我发现了
1 2 | var mydate = new Date('2014-04-03'); console.log(mydate.toDateString()); |
返回"2014年4月2日星期三"。我知道这听起来很疯狂,但有些用户会这样做。
防弹解决方案如下:
1 2 3 4 5 | var parts ='2014-04-03'.split('-'); // Please pay attention to the month (parts[1]); JavaScript counts months from 0: // January - 0, February - 1, etc. var mydate = new Date(parts[0], parts[1] - 1, parts[2]); console.log(mydate.toDateString()); |
1 2 3 | var st ="26.04.2013"; var pattern = /(\d{2})\.(\d{2})\.(\d{4})/; var dt = new Date(st.replace(pattern,'$3-$2-$1')); |
输出将是:
1 | dt => Date {Fri Apr 26 2013} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function stringToDate(_date,_format,_delimiter) { var formatLowerCase=_format.toLowerCase(); var formatItems=formatLowerCase.split(_delimiter); var dateItems=_date.split(_delimiter); var monthIndex=formatItems.indexOf("mm"); var dayIndex=formatItems.indexOf("dd"); var yearIndex=formatItems.indexOf("yyyy"); var month=parseInt(dateItems[monthIndex]); month-=1; var formatedDate = new Date(dateItems[yearIndex],month,dateItems[dayIndex]); return formatedDate; } stringToDate("17/9/2014","dd/MM/yyyy","/"); stringToDate("9/17/2014","mm/dd/yyyy","/") stringToDate("9-17-2014","mm-dd-yyyy","-") |
将它作为参数传递给Date():
1 2 | var st ="date in some format" var dt = new Date(st); |
您可以使用例如:
moment.js(http://momentjs.com/)是一个完整而优秀的使用日期包,并支持ISO 8601字符串。
您可以添加字符串日期和格式。
1 | moment("12-25-1995","MM-DD-YYYY"); |
你可以检查一个日期是否有效。
1 | moment("not a real date").isValid(); //Returns false |
见文档
http://momentjs.com/docs/#/parsing/string-format/
Recommendation: I recommend to use a package for dates that contains a lot of formats because the timezone and format time management is really a big problem, moment js solve a lot of formats. You could parse easily date from a simple string to date but I think that is a hard work to support all formats and variations of dates.
看到0月份给你一月
如果您可以使用极好的时刻库(例如在Node.js项目中),您可以轻松地使用例如解析日期来解析日期。
1 | var momentDate = moment("2014-09-15 09:00:00"); |
并可以通过访问JS日期对象
1 | momentDate ().toDate(); |
对于那些正在寻找一个小巧聪明的解决方案的人:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | String.prototype.toDate = function(format) { var normalized = this.replace(/[^a-zA-Z0-9]/g, '-'); var normalizedFormat= format.toLowerCase().replace(/[^a-zA-Z0-9]/g, '-'); var formatItems = normalizedFormat.split('-'); var dateItems = normalized.split('-'); var monthIndex = formatItems.indexOf("mm"); var dayIndex = formatItems.indexOf("dd"); var yearIndex = formatItems.indexOf("yyyy"); var hourIndex = formatItems.indexOf("hh"); var minutesIndex = formatItems.indexOf("ii"); var secondsIndex = formatItems.indexOf("ss"); var today = new Date(); var year = yearIndex>-1 ? dateItems[yearIndex] : today.getFullYear(); var month = monthIndex>-1 ? dateItems[monthIndex]-1 : today.getMonth()-1; var day = dayIndex>-1 ? dateItems[dayIndex] : today.getDate(); var hour = hourIndex>-1 ? dateItems[hourIndex] : today.getHours(); var minute = minutesIndex>-1 ? dateItems[minutesIndex] : today.getMinutes(); var second = secondsIndex>-1 ? dateItems[secondsIndex] : today.getSeconds(); return new Date(year,month,day,hour,minute,second); }; |
例:
1 2 | "22/03/2016 14:03:01".toDate("dd/mm/yyyy hh:ii:ss"); "2016-03-29 18:30:00".toDate("yyyy-mm-dd hh:ii:ss"); |
如果你想转换格式"dd / MM / yyyy"。这是一个例子:
1 2 3 | var pattern = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/; var arrayDate = stringDate.match(pattern); var dt = new Date(arrayDate[3], arrayDate[2] - 1, arrayDate[1]); |
此解决方案适用于小于9的IE版本。
时间戳应该转换为数字
1 2 3 4 5 | var ts = '1471793029764'; ts = Number(ts); // cast it to a Number var date = new Date(ts); // works var invalidDate = new Date('1471793029764'); // does not work. Invalid Date |
1 2 3 4 5 6 7 8 | var str = 'Sun Apr 25, 2010 3:30pm', timestamp; timestamp = Date.parse(str.replace(/[ap]m$/i, '')); if(str.match(/pm$/i) >= 0) { timestamp += 12 * 60 * 60 * 1000; } |
只是
假设它是正确的格式。
看看datejs图书馆http://www.datejs.com/
转换为pt-BR格式:
1 2 3 4 5 6 7 8 9 10 11 12 13 | var dateString ="13/10/2014"; var dataSplit = dateString.split('/'); var dateConverted; if (dataSplit[2].split("").length > 1) { var hora = dataSplit[2].split("")[1].split(':'); dataSplit[2] = dataSplit[2].split("")[0]; dateConverted = new Date(dataSplit[2], dataSplit[1]-1, dataSplit[0], hora[0], hora[1]); } else { dateConverted = new Date(dataSplit[2], dataSplit[1] - 1, dataSplit[0]); } |
我希望能帮助别人!
我使用此函数将任何Date对象转换为UTC Date对象。
1 2 3 4 5 6 | function dateToUTC(date) { return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()); } dateToUTC(new Date()); |
我为此创建了一个小提琴,您可以在任何日期字符串上使用toDate()函数并提供日期格式。这将返回Date对象。
https://jsfiddle.net/Sus??hil231088/q56yd0rp/
1 | "17/9/2014".toDate("dd/MM/yyyy","/") |
对于在js中сonverting字符串到日期我使用
1 2 3 4 5 6 7 8 | moment().format('MMMM Do YYYY, h:mm:ss a'); // August 16th 2015, 4:17:24 pm moment().format('dddd'); // Sunday moment().format("MMM Do YY"); // Aug 16th 15 moment().format('YYYY [escaped] YYYY'); // 2015 escaped 2015 moment("20111031","YYYYMMDD").fromNow(); // 4 years ago moment("20120620","YYYYMMDD").fromNow(); // 3 years ago moment().startOf('day').fromNow(); // 16 hours ago moment().endOf('day').fromNow(); // in 8 hours |
你可以试试这个:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function formatDate(userDOB) { const dob = new Date(userDOB); const monthNames = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; const day = dob.getDate(); const monthIndex = dob.getMonth(); const year = dob.getFullYear(); // return day + ' ' + monthNames[monthIndex] + ' ' + year; return `${day} ${monthNames[monthIndex]} ${year}`; } console.log(formatDate('1982-08-10')); |
还有另一种方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | String.prototype.toDate = function(format) { format = format ||"dmy"; var separator = this.match(/[^0-9]/)[0]; var components = this.split(separator); var day, month, year; for (var key in format) { var fmt_value = format[key]; var value = components[key]; switch (fmt_value) { case"d": day = parseInt(value); break; case"m": month = parseInt(value)-1; break; case"y": year = parseInt(value); } } return new Date(year, month, day); }; a ="3/2/2017"; console.log(a.toDate("dmy")); // Date 2017-02-03T00:00:00.000Z |
1 | var date = new Date(year, month, day); |
要么
1 | var date = new Date('01/01/1970'); |
格式为'01 -01-1970'的日期字符串在FireFox中不起作用,因此最好在日期格式字符串中使用"/"而不是" -"。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var a ="13:15" var b = toDate(a,"h:m") alert(b); function toDate(dStr, format) { var now = new Date(); if (format =="h:m") { now.setHours(dStr.substr(0, dStr.indexOf(":"))); now.setMinutes(dStr.substr(dStr.indexOf(":") + 1)); now.setSeconds(0); return now; } else return"Invalid Format"; } |
您可以使用正则表达式来解析字符串到详细时间,然后创建日期或任何返回格式,如:
1 2 3 4 5 6 7 8 9 | //example : let dateString ="2018-08-17 01:02:03.4" function strToDate(dateString){ let reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}).(\d{1})/ , [,year, month, day, hours, minutes, seconds, miliseconds] = reggie.exec(dateString) , dateObject = new Date(year, month-1, day, hours, minutes, seconds, miliseconds); return dateObject; } alert(strToDate(dateString)); |
我写了一个可重用的函数,当我从服务器获取日期字符串时使用
您可以传递分隔日期和年份的所需分隔符(/ - 等..)以使用
你可以看到&在这个工作示例上测试它。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <!DOCTYPE html> <html> <head> <style> </style> </head> <body> <span>day: </span> <span id='day'> </span> <span>month: </span> <span id='month'> </span> <span>year: </span> <span id='year'> </span> <br/> <input type="button" id="" value="convert" onClick="convert('/','28/10/1980')"/> <span>28/10/1980 </span> function convert(delimiter,dateString) { var splitted = dateString.split('/'); // create a new date from the splitted string var myDate = new Date(splitted[2],splitted[1],splitted[0]); // now you can access the Date and use its methods document.getElementById('day').innerHTML = myDate.getDate(); document.getElementById('month').innerHTML = myDate.getMonth(); document.getElementById('year').innerHTML = myDate.getFullYear(); } </body> </html> |
如果在转换为Date格式之前需要检查字符串的内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // Convert 'M/D/YY' to Date() mdyToDate = function(mdy) { var d = mdy.split(/[\/\-\.]/, 3); if (d.length != 3) return null; // Check if date is valid var mon = parseInt(d[0]), day = parseInt(d[1]), year= parseInt(d[2]); if (d[2].length == 2) year += 2000; if (day <= 31 && mon <= 12 && year >= 2015) return new Date(year, mon - 1, day); return null; } |
ISO 8601-esque datetrings,与标准一样优秀,仍然没有得到广泛支持。
这是一个很好的资源,可以确定应该使用哪种日期字符串格式:
http://dygraphs.com/date-formats.html
是的,这意味着你的日期字符串可以简单到与之相反
代替
1 2 3 4 5 6 7 8 | //little bit of code for Converting dates var dat1 = document.getElementById('inputDate').value; var date1 = new Date(dat1)//converts string to date object alert(date1); var dat2 = document.getElementById('inputFinishDate').value; var date2 = new Date(dat2) alert(date2); |
使用此代码:(我的问题已通过此代码解决)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function dateDiff(date1, date2){ var diff = {} // Initialisation du retour var tmp = date2 - date1; tmp = Math.floor(tmp/1000); // Nombre de secondes entre les 2 dates diff.sec = tmp % 60; // Extraction du nombre de secondes tmp = Math.floor((tmp-diff.sec)/60); // Nombre de minutes (partie entière) diff.min = tmp % 60; // Extraction du nombre de minutes tmp = Math.floor((tmp-diff.min)/60); // Nombre d'heures (entières) diff.hour = tmp % 24; // Extraction du nombre d'heures tmp = Math.floor((tmp-diff.hour)/24); // Nombre de jours restants diff.day = tmp; return diff; |
}
我已创建parseDateTime函数将字符串转换为日期对象,它在所有浏览器(包括IE浏览器)中工作,检查是否有人需要,参考
https://github.com/Umesh-Markande/Parse-String-to-Date-in-all-browser
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | function parseDateTime(datetime) { var monthNames = [ "January","February","March", "April","May","June","July", "August","September","October", "November","December" ]; if(datetime.split(' ').length == 3){ var date = datetime.split(' ')[0]; var time = datetime.split(' ')[1].replace('.00',''); var timearray = time.split(':'); var hours = parseInt(time.split(':')[0]); var format = datetime.split(' ')[2]; var bits = date.split(/\D/); date = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/ var day = date.getDate(); var monthIndex = date.getMonth(); var year = date.getFullYear(); if ((format === 'PM' || format === 'pm') && hours !== 12) { hours += 12; try{ time = hours+':'+timearray[1]+':'+timearray[2] }catch(e){ time = hours+':'+timearray[1] } } var formateddatetime = new Date(monthNames[monthIndex] + ' ' + day + ' ' + year + ' ' + time); return formateddatetime; }else if(datetime.split(' ').length == 2){ var date = datetime.split(' ')[0]; var time = datetime.split(' ')[1]; var bits = date.split(/\D/); var datetimevalue = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/ var day = datetimevalue.getDate(); var monthIndex = datetimevalue.getMonth(); var year = datetimevalue.getFullYear(); var formateddatetime = new Date(monthNames[monthIndex] + ' ' + day + ' ' + year + ' ' + time); return formateddatetime; }else if(datetime != ''){ var bits = datetime.split(/\D/); var date = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/ return date; } return datetime; } var date1 = '2018-05-14 05:04:22 AM'; // yyyy-mm-dd hh:mm:ss A var date2 = '2018/05/14 05:04:22 AM'; // yyyy/mm/dd hh:mm:ss A var date3 = '2018/05/04'; // yyyy/mm/dd var date4 = '2018-05-04'; // yyyy-mm-dd var date5 = '2018-05-14 15:04:22'; // yyyy-mm-dd HH:mm:ss var date6 = '2018/05/14 14:04:22'; // yyyy/mm/dd HH:mm:ss console.log(parseDateTime(date1)) console.log(parseDateTime(date2)) console.log(parseDateTime(date3)) console.log(parseDateTime(date4)) console.log(parseDateTime(date5)) console.log(parseDateTime(date6)) **Output---** Mon May 14 2018 05:04:22 GMT+0530 (India Standard Time) Mon May 14 2018 05:04:22 GMT+0530 (India Standard Time) Fri May 04 2018 00:00:00 GMT+0530 (India Standard Time) Fri May 04 2018 00:00:00 GMT+0530 (India Standard Time) Mon May 14 2018 15:04:22 GMT+0530 (India Standard Time) Mon May 14 2018 14:04:22 GMT+0530 (India Standard Time) |
另一种方法是在格式字符串上构建一个带有命名捕获组的正则表达式,然后使用该正则表达式从日期字符串中提取日期,月份和年份:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | function parseDate(dateStr, format) { const regex = format.toLocaleLowerCase() .replace(/\bd+\b/, '(?<day>\\d+)') .replace(/\bm+\b/, '(?<month>\\d+)') .replace(/\by+\b/, '(?<year>\\d+)') const parts = new RegExp(regex).exec(dateStr) || {}; const { year, month, day } = parts.groups || {}; return parts.length === 4 ? new Date(year, month-1, day) : undefined; } const printDate = x => console.log(x ? x.toLocaleDateString() : x); printDate(parseDate('05/11/1896', 'dd/mm/YYYY')); printDate(parseDate('07-12-2000', 'dd-mm-yy')); printDate(parseDate('07:12:2000', 'dd:mm:yy')); printDate(parseDate('2017/6/3', 'yy/MM/dd')); printDate(parseDate('2017-6-15', 'y-m-d')); printDate(parseDate('2015 6 25', 'y m d')); printDate(parseDate('2015625', 'y m d')); // bad format |
你也可以这样做:
mydate.toLocaleDateString();
使用这种格式....
1 2 3 4 5 6 7 8 9 10 11 12 | //get current date in javascript var currentDate = new Date(); // for getting a date from a textbox as string format var newDate=document.getElementById("<%=textBox1.ClientID%>").value; // convert this date to date time var MyDate = new Date(newDate); |