JavaScript通过Date-Mask将日期转换成字符串的方法_javascript技巧
程序员文章站
2022-04-26 08:08:29
...
本文实例讲述了JavaScript通过Date-Mask将日期转换成字符串的方法。分享给大家供大家参考。具体实现方法如下:
var MonthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var DayNames = [ "Sunday", "Monday", "Tueday", "Wednesday", "Thursday", "Friday", "Saturday" ]; var ShortMths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var ShortDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; var StringToDate = function (sDate, sFormat, cutOff) { // Input: a date value as a string, it's format as a string e.g. 'dd-mmm-yy' // Optional: a cutoff (integer) for 2 digit years. // If no 'd' appears in the format string then the 1st of the month is assumed. // If the year is 20 and the cut-off is 30 then the value will be converted // to 2020; if the year is 40 then this will be converted to 1940. // If no cut-off is supplied then '20' will be pre-pended to the year (YY). // Output: a string in the format 'YYYY/MM/DD' or '' // Will not attempt to convert certain combinations e.g. DMM, MDD, DDM, YYYYD. var sParsed, fndSingle; // sParsed will be constructed in the format 'YYYY/MM/DD' sDate = sDate.toString().toUpperCase(); sFormat = sFormat.toUpperCase(); if (sFormat.search(/MMMM|MMM/) + 1) { // replace Mar/March with 03, etc. sDate = sDate.replace(new RegExp('(' + ShortMths.join('|') + ')[A-Z]*', 'gi'), function (m) { var i = ShortMths.indexOf(m.charAt(0).toUpperCase() + m.substr(1, 2).toLowerCase()) + 1; return ((i cutOff) ? '19' : '20') : '20'; tempDate += sDate.substr(index + 1); sDate = tempDate; return $1 + $2 + $2; }); sParsed = ('YYYY/MM/DD').replace(/YYYY|MM|DD/g, function(m){ return (sFormat.indexOf(m) + 1) ? sDate.substr(sFormat.indexOf(m), m.length) : ''; }); if (sParsed.charAt(0) == '/') { // if no year specified, assume the current year sParsed = (new Date().getFullYear()) + sParsed; } if (sParsed.charAt(sParsed.length - 1) == '/') { // if no date, assume the 1st of the month sParsed += '01'; } // should end up with 10 characters.. return ( sParsed.length == 10 ) ? sParsed : ''; };
希望本文所述对大家的javascript程序设计有所帮助。
推荐阅读
-
js将字符串转成正则表达式的实现方法_javascript技巧
-
将form表单中的元素转换成对象的方法适用表单提交_javascript技巧
-
将字符串转换成gb2312或者utf-8编码的参数(js版)_javascript技巧
-
将form表单中的元素转换成对象的方法适用表单提交_javascript技巧
-
js将字符串转成正则表达式的实现方法_javascript技巧
-
JavaScript通过字符串调用函数的实现方法_javascript技巧
-
将字符串转换成gb2312或者utf-8编码的参数(js版)_javascript技巧
-
JavaScript通过字符串调用函数的实现方法_javascript技巧
-
javascript将浮点数转换成整数的三个方法_javascript技巧
-
JavaScript将数组转换成CSV格式的方法_javascript技巧