[RESOLVED] Multiple replacement issue
Results 1 to 13 of 13

Thread: [RESOLVED] Multiple replacement issue

  1. #1
    Senior Member Derokorian's Avatar
    Join Date
    Apr 2011
    Location
    Denver
    Posts
    1,774

    resolved [RESOLVED] Multiple replacement issue

    Hey guys,

    I'm trying to extend the Date.prototype with a format function, which accepts a string representing the format desired. All goes well, unless a replacement value contains characters accepted as format characters that haven't yet been processed. My initial thought is to change the format characters from day dd, MM, etc to {dd}, {MM}, etc but this just adds confusion and basically I don't like the idea of the format string being "{yyyy}-{mm}-{dd} {HH}:{mm}". Currently we basically have custom formatting all over the place, and there are bugs where its inconsistent (IE some one didn't know that getMonth was zero-based, etc).

    Basically, I have a chain of if( indexOf > -1) do a replacement. This is what I have so far, and it perfectly shows the issue: jsfiddle

    I'm sure some have run into this issue before, and I've tried searching for "date formatting", "multiple string replacements" and similar searching for language agnostic answers that I could then adapt to JS. I haven't been able to think this through myself.
    Last edited by Derokorian; 12-02-2013 at 05:47 PM.
    Sadly, nobody codes for anyone on this forum. People taste your dishes and tell you what is missing, but they don't cook for you. ~anoopmail
    I'd rather be a comma, then a full stop.
    User Authentication in PHP with MySQLi - Don't forget to mark threads resolved - MySQL(i) warning

  2. #2
    Pna lbh ernq guvf¿
    Join Date
    Jul 2004
    Location
    Kansas City area
    Posts
    19,414
    I'd be interested to see the eloquent solution I'm sure someone already has waiting... but part of me sees this as a sort of state-machine type problem that parses through the format string in one go, using the first character of the special format identifiers as a key. For example, with the format string you have there, you start at the left and work until the end. You encounter a 'y', so you see how many y's you have in a row and consume as many as you can.

    I was bored, so I came up with this (long, ugly) code:

    PHP Code:
    <?php

    // return number of consectutive $char's in $string starting at $offset
    function numConsChars$char$string$offset$max )
        {
        if( 
    $string$offset ] != $char )
            {
            return 
    0;
            }
        else
            {
            for( 
    $num 0;
                 (   ( 
    $num <= $max                )
                  && ( 
    $offset strlen$string ) )
                  && ( 
    $string$offset ] == $char ) );
                 
    $num++, $offset++
               );
           
           return 
    $num;
           }
    }

    function 
    _date_format$fmt )
        {
        
    $ret '';
        
        for( 
    $i 0$i strlen$fmt ); )
            {
            
    // longest format string is 4 ('yyyy')
            
    $num numConsChars$fmt$i ], $fmt$i);

            switch( 
    $fmt$i ] )
                {
                case 
    'y':
                    if( 
    $num == )
                        {
                        
    $ret .= date'Y' );
                        
    $i += 4;
                        }
                    else if( 
    $num == )
                        {
                        
    $ret .= date'y' );
                        
    $i += 2;
                        }
                    else
                        {
                        
    $ret .= 'y';
                        
    $i++;
                        }
                    break;
                
                case 
    'm':
                    if( 
    $num == )
                        {
                        
    $ret .= date'm' );
                        
    $i += 2;
                        }
                    else
                        {
                        
    $ret .= date'n' );
                        
    $i++;
                        }
                    break;
                
                case 
    'M':
                    if( 
    $num == )
                        {
                        
    $ret .= date'F' );
                        
    $i += 2;
                        }
                    else
                        {
                        
    $ret .= date'M' );
                        
    $i++;
                        }
                    break;
                    
                case 
    'D':
                    if( 
    $num == )
                        {
                        
    $ret .= date'l' );
                        
    $i += 2;
                        }
                    else
                        {
                        
    $ret .= date'D' );
                        
    $i++;
                        }
                    break;
                
                case 
    'd':
                    if( 
    $num == )
                        {
                        
    $ret .= date'd' );
                        
    $i += 2;
                        }
                    else
                        {
                        
    $ret .= date'j' );
                        
    $i++;
                        }
                    break;
                
                default:
                    
    $ret .= $fmt$i ];
                    
    $i++;
                    break;
                }
            }

        return 
    $ret;
        }

    echo 
    _date_format'yyyy-yy-MM-M-mm-m-DD-D-dd-d' );
    which outputs this:
    Code:
    2013-13-December-Dec-12-12-Monday-Mon-02-2
    (Yes, I realize the objective was to utilize Javascript, but I prototype random ideas faster in PHP, so sue me. )

  3. #3
    Senior Member Derokorian's Avatar
    Join Date
    Apr 2011
    Location
    Denver
    Posts
    1,774
    Quote Originally Posted by bradgrafelman View Post
    I'd be interested to see the eloquent solution I'm sure someone already has waiting... but part of me sees this as a sort of state-machine type problem that parses through the format string in one go, using the first character of the special format identifiers as a key. For example, with the format string you have there, you start at the left and work until the end. You encounter a 'y', so you see how many y's you have in a row and consume as many as you can.
    Nice, this is exactly the brilliant idea I needed!

    Quote Originally Posted by bradgrafelman View Post
    (Yes, I realize the objective was to utilize Javascript, but I prototype random ideas faster in PHP, so sue me. )
    Ha! You and me both! However, when trying to visualize it in php I always ended up with return $oDate->format($strFormat);
    Sadly, nobody codes for anyone on this forum. People taste your dishes and tell you what is missing, but they don't cook for you. ~anoopmail
    I'd rather be a comma, then a full stop.
    User Authentication in PHP with MySQLi - Don't forget to mark threads resolved - MySQL(i) warning

  4. #4
    Senior Member Derokorian's Avatar
    Join Date
    Apr 2011
    Location
    Denver
    Posts
    1,774
    Hey bg, got it working thanks to your insight! Much appreciated... working version: jsfiddle

    Edit: On github -> https://github.com/derokorian/jsDateFormat
    Last edited by Derokorian; 12-02-2013 at 10:14 PM.
    Sadly, nobody codes for anyone on this forum. People taste your dishes and tell you what is missing, but they don't cook for you. ~anoopmail
    I'd rather be a comma, then a full stop.
    User Authentication in PHP with MySQLi - Don't forget to mark threads resolved - MySQL(i) warning

  5. #5
    Settled 4 red convertible dalecosp's Avatar
    Join Date
    Jul 2002
    Location
    Accelerating Windows at 9.81 m/s....
    Posts
    7,697
    Hey, nice work, Derokorian. Just a note: are you aware of Crockford's insistence on right-aligned brackets in JS?

    The whole lecture is here, and worth the time IMHO: http://www.youtube.com/watch?v=_EANG8ZZbRs

    The exact discussion of this point is here: http://www.youtube.com/watch?v=_EANG8ZZbRs#t=936
    /!!\ mysql_ is deprecated --- don't use it! Tell your hosting company you will switch if they don't upgrade! /!!!\ ereg() is deprecated --- don't use it!

    dalecosp "God doesn't play dice." --- Einstein "Perl is hardly a paragon of beautiful syntax." --- Weedpacket

    Getting Help at All --- Collected Solutions to Common Problems --- Debugging 101 --- Unanswered Posts --- OMBE: Office Machines, Business Equipment

  6. #6
    Senior Member Derokorian's Avatar
    Join Date
    Apr 2011
    Location
    Denver
    Posts
    1,774
    I did not, but a quick search showed me why (since I can't be watching youtube at work). Guess I'll have to update it when I get home. Thanks!
    Sadly, nobody codes for anyone on this forum. People taste your dishes and tell you what is missing, but they don't cook for you. ~anoopmail
    I'd rather be a comma, then a full stop.
    User Authentication in PHP with MySQLi - Don't forget to mark threads resolved - MySQL(i) warning

  7. #7
    Settled 4 red convertible dalecosp's Avatar
    Join Date
    Jul 2002
    Location
    Accelerating Windows at 9.81 m/s....
    Posts
    7,697
    Wow, thankful to God mine's not quite that restrictive ... I have two monitors, and often play Youtube on one (in the background, usually) with the IDE or terminal in the other. As long as it's related to programming, I doubt they even care (I use earbuds a lot). I even see people on FB quite often. Benefits of an elderly, easygoing CEO I guess ;-)
    /!!\ mysql_ is deprecated --- don't use it! Tell your hosting company you will switch if they don't upgrade! /!!!\ ereg() is deprecated --- don't use it!

    dalecosp "God doesn't play dice." --- Einstein "Perl is hardly a paragon of beautiful syntax." --- Weedpacket

    Getting Help at All --- Collected Solutions to Common Problems --- Debugging 101 --- Unanswered Posts --- OMBE: Office Machines, Business Equipment

  8. #8
    Senior Member Derokorian's Avatar
    Join Date
    Apr 2011
    Location
    Denver
    Posts
    1,774
    Yeah, the new place seems pretty darn lenient and easy going. But being as I've been there less than a month I'm not going to go out of my way to push my luck. I couldn't be happier being there, and don't want to risk it

    Anyway, updated braces and improved defaulting for localization.

    Any feedback is welcome, or just make the changes and do a pull request
    Sadly, nobody codes for anyone on this forum. People taste your dishes and tell you what is missing, but they don't cook for you. ~anoopmail
    I'd rather be a comma, then a full stop.
    User Authentication in PHP with MySQLi - Don't forget to mark threads resolved - MySQL(i) warning

  9. #9
    Un Re Member cretaceous's Avatar
    Join Date
    Sep 2004
    Location
    London UK
    Posts
    940
    Hey - interesting video - had to keep telling myself: this is a vid on js not php
    but going to the abyss - yep
    it's funny.. sometimes a bug is exciting - it's a challenge and only you can fix it ! (and of course you put it there in the first place.. and hid it really well)

  10. #10
    Senior Member
    Join Date
    Jul 2007
    Posts
    3,647
    Nice job Derokorian. I havn't had to deal with this for a long time, so I don't really have a working knowledge of actual use cases. But one thought I got while reading this was that it could perhaps be useful to separate the format string parsing from output generation. That way you could parse the format string and then use it for both input and output. On the other hand, if you use a date picker for date input, I suppose there would be no need to parse input.

    Thanks for the youtube link dalecosp

  11. #11
    Settled 4 red convertible dalecosp's Avatar
    Join Date
    Jul 2002
    Location
    Accelerating Windows at 9.81 m/s....
    Posts
    7,697
    Quote Originally Posted by johanafm View Post
    Thanks for the youtube link dalecosp
    You're welcome. I love PHP, and it has brought me a long way --- I found a career with it. That said, it seems impossible to do well with the WWW anymore if you're not a JS programmer as well, so I've been paying a lot of attention to Crockford. He's not the only resource available, but he is a very good presenter and has some excellent points to make.

    If anyone *isn't* much of a JS guru (like me ), I'd certainly recommend his 3-part course from Yahoo! a few years back, or any of his newer stuff, although he's changed the titles to be "fancier" and you may get something more advanced than you need if you just watch *anything* he's got out there.
    /!!\ mysql_ is deprecated --- don't use it! Tell your hosting company you will switch if they don't upgrade! /!!!\ ereg() is deprecated --- don't use it!

    dalecosp "God doesn't play dice." --- Einstein "Perl is hardly a paragon of beautiful syntax." --- Weedpacket

    Getting Help at All --- Collected Solutions to Common Problems --- Debugging 101 --- Unanswered Posts --- OMBE: Office Machines, Business Equipment

  12. #12
    Senior Member Derokorian's Avatar
    Join Date
    Apr 2011
    Location
    Denver
    Posts
    1,774
    Thanks johanafm. The specific use case that made me make this was pretty simple. We had quite a few different format functions in order to get the different output we wanted. I thought 'gee why doesn't js date object have a formatting option much like PHP and .NET' so bam. Now it does with this script. Still working on improving it though. But I can definitely see it being useful.

    PS. I've started working on parseFormat which is the reverse based on your suggestion. Still new to trying to open source things, so I'm not sure if it should somehow be part of this git or in its own.
    Sadly, nobody codes for anyone on this forum. People taste your dishes and tell you what is missing, but they don't cook for you. ~anoopmail
    I'd rather be a comma, then a full stop.
    User Authentication in PHP with MySQLi - Don't forget to mark threads resolved - MySQL(i) warning

  13. #13
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Thrilled To Be Here"
    Posts
    21,863
    I've just watched the video. Very interesting, and actually helped explain something about my "style".

    I usually put braces on the left, except in JavaScript, where I put them on the right. Until now though I would have had a hard time articulating why. The video gives a rational explanation.

    So was my choice decided by System One or System Two?
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •