Go Back   CodingForums.com > :: Client side development > JavaScript programming > Post a JavaScript

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 04-30-2011, 03:42 PM   PM User | #1
AndrewGSW
Senior Coder

 
Join Date: Apr 2011
Location: London, England
Posts: 2,120
Thanks: 15
Thanked 354 Times in 353 Posts
AndrewGSW will become famous soon enough
Convert string to date

If you supply the following function with a date as a string '20/4/2011' and a corresponding format descriptor 'dd/m/yyyy' it will return another string in the format '2011/04/20'. This returned value can be used to create a valid Date variable.
Code:
var myDate = StringToDate('20/4/2011','dd/m/yyyy');
var actualDate;
if ( myDate != '' ) actualDate = new Date(myDate);
You can also supply a third argument to handle two digit years. (Note that it will not handle confusing formats such as 'ddm', but will correctly handle the variable lengths of month and day names.)
It requires ShortMths and ShortDays (but I've posted MonthNames and DayNames as well):
Code:
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"];
Code:
function StringToDate(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
    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 < 10) ? "0" + i : "" + i).toString();
        });
        sFormat = sFormat.replace(/MMMM|MMM/g, 'MM');
    }
    if (sFormat.search(/DDDD|DDD/) + 1) {		// replace Tue/Tuesday, etc. with ''
        sDate = sDate.replace(new RegExp('(' + ShortDays.join('|') + ')[A-Z]*', 'gi'), '');
        sFormat = sFormat.replace(/DDDD|DDD/g, '');
    }
    sDate = sDate.replace(/(^|\D)(\d)(?=\D|$)/g, function($0, $1, $2){	// single digits 2 with 02
        return $1 + '0' + $2;
    });
    sFormat = sFormat.replace(/(^|[^DMY])(D|M)(?=[^DMY]|$)/g, function($0, $1, $2){
        return $1 + $2 + $2;		// replace D or M with DD and MM
    });
    fndSingle = sFormat.search(/(^|[^D])D([^D]|$)|(^|[^M])M([^M]|$)/)+1;	// are there still single Ds or Ms?
    if ( fndSingle ) return '';		// do not attempt to parse, for example, 'DMM'
    sFormat = sFormat.replace(/(^|[^Y])(YY)(?=[^Y]|$)/g, function($0, $1, $2, index){
        var tempDate = sDate.substr(0, index + 1);
        tempDate += (cutOff) ? ((parseInt(sDate.substr(index + 1, 2)) > 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';
    }
    return ( sParsed.length == 10 ) ? sParsed : '';	// should end up with 10 characters..
}
I have also used it to correctly sort tables by date columns. Andy.
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS
AndrewGSW is offline   Reply With Quote
Old 05-12-2011, 11:29 AM   PM User | #2
Kor
Red Devil Mod


 
Kor's Avatar
 
Join Date: Apr 2003
Location: Bucharest, ROMANIA
Posts: 8,478
Thanks: 58
Thanked 379 Times in 375 Posts
Kor has a spectacular aura aboutKor has a spectacular aura about
To avoid confusion and possible errors, usually the problem is solved otherwise. The developer should simply used 3 different elements (text boxes or even better related select boxes) for year, month and date. No need for further intricate conversions, presumptions, validations, and so on. The KISS principle, you know...
__________________
KOR
Offshore programming
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

Last edited by Kor; 05-12-2011 at 11:32 AM..
Kor is offline   Reply With Quote
Old 05-13-2011, 12:15 AM   PM User | #3
AndrewGSW
Senior Coder

 
Join Date: Apr 2011
Location: London, England
Posts: 2,120
Thanks: 15
Thanked 354 Times in 353 Posts
AndrewGSW will become famous soon enough
Quote:
Originally Posted by Kor View Post
To avoid confusion and possible errors, usually the problem is solved otherwise. The developer should simply used 3 different elements (text boxes or even better related select boxes) for year, month and date. No need for further intricate conversions, presumptions, validations, and so on. The KISS principle, you know...
I agree, and wouldn't use my function for form validation of a date. I built it because I wanted to sort a column of dates in a table (and wasn't happy with the methods I found elsewhere).
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS
AndrewGSW is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 08:30 AM.


Advertisement
Log in to turn off these ads.