Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 12 of 12
  1. #1
    Regular Coder
    Join Date
    Sep 2002
    Posts
    462
    Thanks
    0
    Thanked 20 Times in 20 Posts

    try catch or another way...

    Ok I have a script that uses some global arrays and a function that looks like this:
    function functName(p)

    The other params are optional so they are accessed using:
    functName.arguments[1] etc.

    My problem is an error that I can't seem to catch even though it's an easy one.
    array = (functName.arguments[1] != undefined && evel('window.' +functName.arguments[1]) != undefined) ? do this: or this;

    The second param is an arrayName. It can be sent to the function as a string or a reference ( string: 'arrayName' , ref: arrayName) both operate correctly unless the array doesn't exist. Entered as a string, if the array doesn't exist it defaults to another array as required. However, if posted as a reference and it doesn't exist it throws an error: 'arrayName' is undefined

    Should I just use a 'try catch' method or it just something simple I missed?
    NO Limits!! DHCreationStation.com
    ------------------------------------------------------------
    For projects using MediaTypes (MIMETypes) visit E-BAM.net -(updated weekly)

    Broken items wanted for tinkerin'! PostItNow@BrokenEquipment.com
    Global Complaint Dept.

  • #2
    Senior Coder
    Join Date
    Mar 2005
    Location
    Portsmouth UK
    Posts
    4,535
    Thanks
    3
    Thanked 513 Times in 500 Posts
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
      <title></title>
    </head>
    
    <body>
    
    <script type="text/javascript">
    /*<![CDATA[*/
    function functName(p){
     var args=functName.arguments;
     if (!args[1]||(typeof(args[1])=='string'?!window[args[1]]:typeof(args[1])!='object')){
      return alert('no args[1]');
     }
     alert(p);
    }
    
    var ary=['tom'];
    
    functName('1')
    functName('2','ary')
    functName('3',ary)
    /*]]>*/
    </script>
    </body>
    
    </html>
    Vic

    God Loves You and will never love you less.

    http://www.vicsjavascripts.org/Home.htm

    If my post has been useful please donate to http://www.operationsmile.org.uk/

  • #3
    Regular Coder
    Join Date
    Sep 2002
    Posts
    462
    Thanks
    0
    Thanked 20 Times in 20 Posts
    Thanks Vic, but it didn't work...I still got the same error so I guess I'll have to post the code:
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
    <title></title>
    </head>
    
    <body>
    
    <script text="text/javascript">
    /*------------------------------------------------------------------
    //                      'csDateStamp' function                    //
    //                        Copyright (c) 2012                      //
    //                     DH Creation Station(tm)                    //
    //             =======================================            //
    //             Original Copyrights Must Remain Intact             //
    //                    For All Intended Purposes!!                 //
    //----------------------------------------------------------------//
    [Created - 2012.04.21 - core.function{csDateStamp} - ver: 0.1.3]
    Description:
    Replace formatted date & time input strings with stamp variables
    and return adjusted string to caller for posting.
    
    Reasoning:
    Needed db date/time input function and decided to take it further
    so it could be used for db date/time, copyright, legal forms, live
    clocks etc..
    
    Current Variables: (Last Updated - 2012.04.24)
    {- Date/Time Variables -}
    'StmpLocalTime' - returns full local date/time.
    'StmpUTD'       - returns full date/time.
    
    
    {- Date Variables -}
    'StmpYearFull'  - returns FullYear. '2012'
    'StmpYearAbv'   - returns FullYearAbv. '12'
    
    'StmpMonthFull' - returns FullMonth from 'DStmpMonthsOfYear' array. 'April'
    'StmpMonthAbv'  - returns FullMonthAbv. from 'DStmpMonthsOfYear' array. 'Apr'
    'StmpMonthDN'   - returns FullMonth as DblNum. '04'
    'StmpMonthN'    - returns FullMonth as Num. '4'
    
    'StmpDayFull' - returns FullDay from 'DStmpDaysOfWeek' array. 'Monday'
    'StmpDayAbv'  - returns FullDyaAbrv. from 'DStmpDaysOfWeek' array. 'Mon'
    'StmpDayDN'   - returns FullDayDblNum . '02'
    'StmpDayN'    - returns FullDayNum . '2'
    
    'StmpDateSuffix' - returns required suffix from 'DStmpDateSuffix' array. 'nd'
    'StmpDateFull'   - returns FullDate with required suffix. '22nd'
    'StmpDateDN'     - returns FullDateDblNum . '02'
    'StmpDateN'      - returns FullDayNum . '2'
    
    
    {- Time Variables -}
    'StmpHourFull' - returns FullHours with 'DStmpTimeIncrements'. '10:Hours'
    'StmpHourAbv'  - returns FullHoursAbrv. with 'DStmpTimeIncrementsAbv'. '10:Hrs'
    'StmpHourDN'   - returns FullHoursDblNum. '09'
    'StmpHourN'    - returns FullHoursNum . '9'
    'Stmp12HourDN' - returns 12Hour clock style DblNum. '09'
    'Stmp12HourN'  - returns 12Hour clock style Num. '9'
    'StmpTOD'      - returns required clock style time of day from 'DStmpTimeOfDay' array. 'PM'
    'StmpSmTOD'    - returns lower case clock style tod from 'DStmpTimeOfDay' array. 'pm'
    
    'StmpMinuteFull' - returns FullMinutes with 'DStmpTimeIncrements'. '9:Minutes'
    'StmpMinuteAbv'  - returns FullMinutesAbrv. with 'DStmpTimeIncrementsAbv'. '9:Mins'
    'StmpMinuteDN'   - returns FullMinutesDblNum. '09'
    'StmpMinuteN'    - returns FullMinutesNum . '9'
    
    'StmpSecondFull' - returns FullSeconds with 'DStmpTimeIncrements'. '9:Seconds'
    'StmpSecondAbv'  - returns FullSecondsAbrv. with 'DStmpTimeIncrementsAbv'. '9:Secs'
    'StmpSecondDN'   - returns FullSecondsDblNum. '09'
    'StmpSecondN'    - returns FullSecondsNum . '9'
    
    'StmpMilliSecondFull' - returns FullMilliSeconds with 'DStmpTimeIncrements'. '9:Milliseconds'
    'StmpMilliSecondAbv'  - returns FullSecondsAbrv. with 'DStmpTimeIncrementsAbv'. '9:Mils'
    'StmpMilliSecondDN'   - returns FullSecondsDblNum. '09' ????
    'StmpMilliSecondN'    - returns FullSecondsNum . '9' ????
    
    
    Options:
    [Added - 2012.04.24] DateStamp (Presets) Arrays
    ------------------------------------------------------------------
    Added the use of preset arrays to speed up processing when
    particular objects are known to the user. These arrays can
    be named anything but should contain the 'DStmp' tag so user
    knows the array works with the 'csDateStamp' function. If
    using a number in the first portion of the array name include
    an underscore.
    Example Array:
    var _12HourClockDStmp = ['Stmp12HourN','StmpMinuteDN','StmpTOD'];
    
    Example FunctionCall:
    csDateStamp('Stmp12HourN:StmpMinuteDN StmpTOD','_12HourClockDStmp');
    would return - 1:05 PM
    
    Presets can be accessed by sending the array name as a string or
    array reference.
    Example string:
    csDateStamp('Stmp12HourN:StmpMinuteDN StmpTOD','_12HourClockDStmp');
    
    Example reference:
    csDateStamp('Stmp12HourN:StmpMinuteDN StmpTOD',_12HourClockDStmp);
    
    
    
    [Added - 2012.04.24] DateStamp (Languages) Arrays
    ------------------------------------------------------------------
    Other arrays such as 'MonthOfYear', 'TimeOfDay' etc. are used
    outside the main function so user has a 'multi-language' option
    defined by the two letter identifier.
    Example: EN_DStmpMonthsOfYear
    
    The default language is English 'EN'. The third function parameter
    will allow user to change languages accordingly. To create a new
    language simply copy & paste the 'EN_DStmp' arrays. Change 'EN'
    to the two letter identifier and change array contents.
    ------------------------------------------------------------------*/
    
    
    
    
    
    //----- Language Arrays (Defaults to 'EN_DStmp' default arrays) -----//
    var EN_DStmpMonthsOfYear = ['January','February','March','April','May','June','July','August','September','October','November','December'];
    var EN_DStmpDaysOfWeek = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
    var EN_DStmpDateSuffix = ['st','nd','rd','th'];
    
    var EN_DStmpTimeIncrements = ['Hour','Minute','Second','Millisecond'];
    var EN_DStmpTimeIncrementsAbv = ['Hr','Min','Sec','Mil'];
    var EN_DStmpTimeOfDay = ['AM','PM'];
    var EN_DStmpPlural = 's';
    
    
    
    
    //----- DateStamp Presets (Defaults to 'DStmpDefault' local array) -----//
    var _12HourClockDStmp = ['Stmp12HourN','StmpMinuteDN','StmpSmTOD'];
    var _24HourClockDStmp = ['StmpHourDN','StmpMinuteDN','StmpSecondDN','StmpTOD'];
    var dbDStmp           = ['StmpYearFull','StmpMonthDN','StmpDayDN','StmpHourDN','StmpMinuteDN','StmpSecondDN'];
    
    
    
    
    function csDateStamp(c){//copyright 2012 DH Creation Station. All Rights Reserved!
    	var tmp = c, msg = '';
    	
    	
    	//----- Set Language Reference Arrays -----//
    	var required = ['DStmpMonthsOfYear','DStmpMonthsOfYear','DStmpDaysOfWeek','DStmpDateSuffix','DStmpTimeIncrements','DStmpTimeIncrementsAbv','DStmpTimeOfDay','DStmpPlural'];
    	var language = (csDateStamp.arguments[2] != undefined)? csDateStamp.arguments[2].toUpperCase()+'_':'EN_';
    	for(var i=0;i<required.length;i++){ eval('var '+ required[i]+' =' +language + required[i]); }
    	
    	
    	
    	//--- Get All Date Variables ---//
    	var now = new Date();
    	
    	//----- Date/Time Vars -----//
    	var StmpLocalTime = now.toString();
    	var StmpUTD = now.toGMTString();
    	
    	
    	//----- Date Vars -----//
    	var StmpYearFull  = now.getFullYear();
    	var StmpYearAbv   = StmpYearFull.toString().substring(2,4);
    	
    	var dsMonth       = now.getMonth();
    	var StmpMonthFull = DStmpMonthsOfYear[dsMonth];
    	var StmpMonthAbv  = DStmpMonthsOfYear[dsMonth].substring(0,3);
    	var StmpMonthDN   = (dsMonth+1 <=9) ? '0' + (dsMonth+1) : dsMonth+1;
    	var StmpMonthN    = dsMonth+1;
    	
    	var dsDay       = now.getDay();
    	var StmpDayFull = DStmpDaysOfWeek[dsDay];
    	var StmpDayAbv  = DStmpDaysOfWeek[dsDay].substring(0,3);
    	var StmpDayDN   = (dsDay+1 <=9) ? '0' + (dsDay+1) : dsDay+1;
    	var StmpDayN    = dsDay+1;
    	
    	var dsDate         = now.getDate();
    	var StmpDateSuffix = '';
    	if((dsDate >=4 && dsDate <=20) ||(dsDate >= 24 && dsDate <= 30)){ StmpDateSuffix = DStmpDateSuffix[3]; }
    	else{
    		if(dsDate == 1 || dsDate == 21 || dsDate == 31){ StmpDateSuffix = DStmpDateSuffix[0]; }
    		if(dsDate == 2 || dsDate == 22){ StmpDateSuffix = DStmpDateSuffix[1]; }
    		if(dsDate == 3 || dsDate == 23){ StmpDateSuffix = DStmpDateSuffix[2]; }
    	}
    	
    	var StmpDateFull = dsDate + StmpDateSuffix;
    	var StmpDateDN   = (dsDate <=9) ? '0' + (dsDate) : dsDate;
    	var StmpDateN    = dsDate;
    	
    	
    	//----- Time Vars -----//
    	var dsHours      = now.getHours();
    	var StmpTOD      = (dsHours < 12) ? DStmpTimeOfDay[0]: DStmpTimeOfDay[1];
    	var StmpSmTOD    = StmpTOD.toLowerCase();
    	var HoursPlural  = (dsHours != 1) ? DStmpPlural : '';
    	var StmpHourFull = dsHours + ':' + DStmpTimeIncrements[0] + HoursPlural;
    	var StmpHourAbv  = dsHours + ':' + DStmpTimeIncrementsAbv[0] + HoursPlural;
    	var StmpHourDN   = (dsHours <=9) ? '0' + dsHours : dsHours;
    	var StmpHourN    = dsHours;
    	
    	var Stmp12HourDN = (dsHours > 12) ? ((dsHours - 12) <= 9 ) ? '0' + (dsHours - 12):(dsHours - 12):(dsHours <= 9) ? '0' + dsHours: dsHours;
    	var Stmp12HourN  = (dsHours > 12) ? (dsHours - 12) : dsHours;
    	
    	
    	var dsMinutes      = now.getMinutes();
    	var MinutesPlural  = (dsMinutes != 1) ? DStmpPlural : '';
    	var StmpMinuteFull = dsMinutes + ':' + DStmpTimeIncrements[1] + MinutesPlural;
    	var StmpMinuteAbv  = dsMinutes + ':' + DStmpTimeIncrementsAbv[1] + MinutesPlural;
    	var StmpMinuteDN   = (dsMinutes <=9) ? '0' + dsMinutes : dsMinutes;
    	var StmpMinuteN    = dsMinutes;
    	
    	var dsSeconds      = now.getSeconds();
    	var SecondsPlural  = (dsSeconds != 1) ? DStmpPlural : '';
    	var StmpSecondFull = dsSeconds + ':' + DStmpTimeIncrements[2] + SecondsPlural;
    	var StmpSecondAbv  = dsSeconds + ':' + DStmpTimeIncrementsAbv[2] + SecondsPlural;
    	var StmpSecondDN   = (dsSeconds <=9) ? '0' + dsSeconds : dsSeconds;
    	var StmpSecondN    = dsSeconds;
    	
    	var dsMilliSeconds      = now.getMilliseconds();
    	var MilliSecondsPlural  = (dsMilliSeconds != 1) ? DStmpPlural : '';
    	var StmpMilliSecondFull = dsMilliSeconds + ':' + DStmpTimeIncrements[3] + MilliSecondsPlural;
    	var StmpMilliSecondAbv  = dsMilliSeconds + ':' + DStmpTimeIncrementsAbv[3] + MilliSecondsPlural;
    	var StmpMilliSecondDN   = (dsMilliSeconds <=9) ? '0' + dsMilliSeconds : dsMilliSeconds;
    	var StmpMilliSecondN    = dsMilliSeconds;
    	
    	
    	//----- Stamp Variables (must remain in funxtion) -----//
    	var DStmpDefault = [];
    	DStmpDefault[0] = 'StmpLocalTime';
    	DStmpDefault[1] = 'StmpUTD';
    	DStmpDefault[2] = 'StmpYearFull';
    	DStmpDefault[3] = 'StmpYearFull';
    	DStmpDefault[4] = 'StmpYearAbv';
    	DStmpDefault[5] = 'StmpMonthFull';
    	DStmpDefault[6] = 'StmpMonthAbv';
    	DStmpDefault[7] = 'StmpMonthDN';
    	DStmpDefault[8] = 'StmpMonthN';
    	DStmpDefault[9] = 'StmpDayFull';
    	DStmpDefault[10] = 'StmpDayAbv';
    	DStmpDefault[11] = 'StmpDayDN';
    	DStmpDefault[12] = 'StmpDayN';
    	DStmpDefault[13] = 'StmpDateFull';
    	DStmpDefault[14] = 'StmpDateDN';
    	DStmpDefault[15] = 'StmpDateN';
    	DStmpDefault[16] = 'StmpTOD';
    	DStmpDefault[17] = 'StmpSmTOD';
    	DStmpDefault[18] = 'StmpHourFull';
    	DStmpDefault[19] = 'StmpHourAbv';
    	DStmpDefault[20] = 'StmpHourDN';
    	DStmpDefault[21] = 'StmpHourN';
    	DStmpDefault[22] = 'Stmp12HourDN';
    	DStmpDefault[23] = 'Stmp12HourN';
    	DStmpDefault[24] = 'StmpMinuteFull';
    	DStmpDefault[25] = 'StmpMinuteAbv';
    	DStmpDefault[26] = 'StmpMinuteDN';
    	DStmpDefault[27] = 'StmpMinuteN';
    	DStmpDefault[28] = 'StmpSecondFull';
    	DStmpDefault[29] = 'StmpSecondAbv';
    	DStmpDefault[30] = 'StmpSecondDN';
    	DStmpDefault[31] = 'StmpSecondN';
    	DStmpDefault[32] = 'StmpMilliSecondFull';
    	DStmpDefault[33] = 'StmpMilliSecondAbv';
    	DStmpDefault[34] = 'StmpMilliSecondDN';
    	DStmpDefault[35] = 'StmpMilliSecondN';
    	
    	
    	//----- process variables -----//
    	var array = (csDateStamp.arguments[1] != undefined && eval('window.'+csDateStamp.arguments[1]) != undefined)? eval(csDateStamp.arguments[1]):eval(DStmpDefault);
    	
    	for(var cs=0;cs<array.length;cs++){
    		var re = new RegExp(array[cs], "g");
    		tmp = tmp.replace(re, eval(array[cs]));
    	}
    	
    	//alert( tmp );
    	return tmp
    	
    	
    	/*-------------------------------------------------------------------------
    	[Problem]
    	a 'DateStamp Preset' can be sent to the function as a string or array
    	reference. When sent as a string if the array does not exist it uses
    	'DStmpDefault' array as required to fullfill the function. However when
    	sent as an array reference it pulls an error.
    	-------------------------------------------------------------------------*/
    }
    </script>
    
    
    12Hour Clock Example<br>
    <script>document.write(csDateStamp('Stmp12HourN:StmpMinuteDN StmpSmTOD', '_12HourClock'))</script>
    <br><br>
    
    <!--//
    24Hour Clock Example<br>
    <script>document.write(csDateStamp('StmpHourDN:StmpMinuteDN:StmpSecondDN StmpTOD','_24HourClockDStmp'))</script>
    <br><br>
    
    DB Date & Time Entry Example<br>
    <script>document.write(csDateStamp('StmpYearFull-StmpMonthDN-StmpDayDN StmpHourDN:StmpMinuteDN:StmpSecondDN','dbDStmp'))</script>
    <br><br>
    
    
    
    
    
    
    Current Local Time Example<br>
    <script>document.write(csDateStamp('StmpLocalTime'))</script>
    <br><br>
    
    
    Document Example<br>
    <script>document.write(csDateStamp('On this, the StmpDateFull day of StmpMonthFull of the year StmpYearFull ...'))</script>
    <br><br>
    
    Database Date/Time Entry<br>
    <script>document.write(csDateStamp('StmpYearFull-StmpMonthDN-StmpDayDN StmpHourDN:StmpMinuteDN:StmpSecondDN:StmpMilliSecondDN'))</script>
    <br><br>
    
    
    Database Date/Time Entry<br>
    <script>document.write(csDateStamp('StmpHourFull StmpMinuteFull StmpSecondFull StmpMilliSecondFull'))</script>
    <br><br>
    
    
    Database Date/Time Entry<br>
    <script>document.write(csDateStamp('StmpHourAbv StmpMinuteAbv StmpSecondAbv StmpMilliSecondAbv'))</script>
    <br><br>
    
    
    Database Date/Time Entry<br>
    <script>document.write(csDateStamp('StmpHourAbv:StmpMinuteAbv StmpSmTOD Stmp12HourDN Stmp12HourN'))</script>
    <br><br>
    
    //-->
    
    
    </body>
    
    </html>
    Ok, in the 12Hour Clock Example the array name is '_12HourClockDStmp'. If sent as a string or reference it's it accesses the array. If you use '_12HourClock' as a string it uses the default array as required. If sent as _12HourClock it returns an error I can't seem to catch. I got a feelin' if I can't get that working correctly then the Language and other options that will be added won't work either.

    And for those who don't like the use of 'document.write' it's just a demo to get the main function working...get over it.
    NO Limits!! DHCreationStation.com
    ------------------------------------------------------------
    For projects using MediaTypes (MIMETypes) visit E-BAM.net -(updated weekly)

    Broken items wanted for tinkerin'! PostItNow@BrokenEquipment.com
    Global Complaint Dept.

  • #4
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,075
    Thanks
    0
    Thanked 256 Times in 252 Posts
    Eval is unnecessary. You can accomplish the same thing with more efficiency and flexibility using the square bracket notation. And also, you don't have to specify the function name to access the arguments, you can access it directly.

    Try this:
    Code:
    var array = (arguments[1] != undefined && window[arguments[1]] != undefined) ? window[arguments[1]] : DStmpDefault;
    You don't have to eval DStmpDefault as it is a local variable and is already an array object.
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,650
    Thanks
    80
    Thanked 4,638 Times in 4,600 Posts
    You know, there *IS* an easier way than mucking with the arguments array.

    Code:
    function csDateStamp(c,array,language)
    {
    	var tmp = c, msg = '';
            if ( array == null ) array = DStmpDefault;
    	if ( language == null ) language = "EN_";
            ....
    I do this all the time. And lots and lots of code does it when detecting whether or not the event argument has been passed to an event handler (normal) or is missing (older MSIE).

    I can understand mucking with the arguments array if the order and type of arguments might depend on preceding arguments, but if the order and meaning of a given position is fixed (e.g., in this case arguments[2] is always language), then why bother?
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,650
    Thanks
    80
    Thanked 4,638 Times in 4,600 Posts
    There's also simpler way to do the substitutions eval() or even the window[...] notation.

    Really simple. Partial example:
    Code:
        var availableValues = {
        	'StmpLocalTime' : now.toString(),
    	'StmpUTD' : now.toGMTString(),
    	'StmpYearFull' : now.getFullYear(),
            ...
        };
    
        if ( array == null )
        {
            for ( var name in availableValues )
            {
                var re = new RegExp( name, "g");
    	    tmp = tmp.replace( re, availableValues[name] ;
    	} 
       } else {
           ... not clear what your intent is here with custom array passed in ...
       }
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #7
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,650
    Thanks
    80
    Thanked 4,638 Times in 4,600 Posts
    Similarly, you can avoid all the eval() crud on the stuff based on language thus:
    Code:
    var languages = {
        "EN_" : {
            "Months" : ['January','February','March','April','May','June',
                                             'July','August','September',
                                             'October','November','December'],
            "Days" : ['Sunday','Monday','Tuesday','Wednesday',
                                           'Thursday','Friday','Saturday'],
            "DateSuffixes" : ['st','nd','rd','th'],
            ... etc. ...
       },
       "FR_" : {
             ... french ...
       },
       ... etc. ...
    };
    Then you would do something like
    Code:
    var names = languages[language]
    And when you needed a day of the week:
    Code:
        var dayName = names["Days"][3]; // "Wednesday"
    Note that you don't need all the ugly "DStmp" prefixes, because the scope of the names is limited to within the languages object.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,650
    Thanks
    80
    Thanked 4,638 Times in 4,600 Posts
    p.s.: Your date suffixes isn't really complete, at all. For example, Russian adjectival suffixes have to agree with the GENDER of the thing they are modifying, not just the number per se. I'm pretty sure other languages do that, too.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #9
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,650
    Thanks
    80
    Thanked 4,638 Times in 4,600 Posts
    I know I shouldn't do this, but I had to give it a shot.

    My simple-minded version of date formatting:
    Code:
    <html>
    <body>
    <script type="text/javascript">
    /*
     * Date.format( )  
     *
     * Alters the Date object prototype to provide a method
     * that parallels MySQLs FORMAT_DATE function.
     * 
     * There are some important differences in the designators, so watch out.
     * 
     * AVAILABLE FORMAT SPECIFIERS:
    
    %a 	Numeric day of the week (0=Sunday..6=Saturday)
    %A 	Numeric day of the week (0=Monday..6=Sunday)
    
    %b 	Abbreviated month name (Jan..Dec)
    %B 	Month name (January..December)
    
    %d 	Day of the month, numeric (01..31)
    %D 	Day of the month with suffix (1st, 2nd, 3rd, …)
    
    %h 	Hour (01..12)
    %H 	Hour (00..23)
    
    %j 	Day of year (001..366)
    
    %M,%m 	Month, numeric (01..12)
    %N,%n 	Minutes, numeric (00..59)
    
    %P 	AM or PM
    %p 	am or pm
    
    %S,%s 	Seconds (00..59)
    
    %T 	Time, 24-hour (hh:mm:ss)
    %t 	Time, 12-hour (hh:mm:ss followed by AM or PM)
    
    %w 	Abbreviated weekday name (Sun..Sat)
    %W 	Weekday name (Sunday..Saturday)
    
    %y 	Year, numeric (two digits)
    %Y 	Year, numeric, four digits
    
    %% 	A literal “%” character
     
     *
     *******************************************************
     */
    
    Date.prototype.format = function(formatString,useUTC) 
    {
        if ( formatString == null ) formatString = "%W, %B %d, %Y"; // change default as you wish!
        if ( useUTC == null ) useUTC = false; // change default as you wish!
    
        var DOW = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
        var dow = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
        var MOY = ["January","February","March","April","May","June","August",
                   "September","October","November","December" ];
        var moy = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
        var suf = ["st","nd","rd","th","th","th","th","th","th","th",
                   "th","th","th","th","th","th","th","th","th","th",
                   "st","nd","rd","th","th","th","th","th","th","th",
                   "st"];
    
    
        var result = "";
    
        if ( useUTC ) {
            this.setTime( this.getTime() + this.getTimezoneOffset() * 60000 );
        }
    
        var cnum = 0;
        var temp;
        while ( cnum < formatString.length )
        {
            var char = formatString.charAt(cnum);
            if ( char != "%" )
            {
                result += char; 
            } else {
                ++cnum;
                var char = formatString.charAt(cnum);
                switch ( char )
                {
                    case "a":
                        result += this.getDay(); break;
                    case "A": 
                        result += ( 6 + this.getDay() ) % 7; break;
                    case "b":
                        result += moy[ this.getMonth() ]; break;
                    case "B":
                        result += MOY[ this.getMonth() ]; break;
                    case "d":
                        temp = this.getDate();
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp; break;               
                    case "D":
                        temp = this.getDate();
                        result += temp + suf[temp-1]; break;
                    case "h":
                        temp = this.getHours();
                        if ( temp == 0 || temp > 12 ) temp -= 12;
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp; break;               
                    case "H":
                        temp = this.getHours();
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp; break;               
                    case "m": case "M":
                        temp = 1 + this.getMonth();
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp; break;               
                    case "n": case "N":
                        temp = this.getMinutes();
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp; break;               
    		case "p": 
                        result += ( this.getHours() < 12 ) ? "am" : "pm"; break;
    		case "P": 
                        result += ( this.getHours() < 12 ) ? "AM" : "PM"; break;
                    case "s": case "S":
                        temp = this.getSeconds();
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp; break;               
                    case "T":
                        temp = this.getHours();
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp + ":";
                        temp = this.getMinutes();
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp + ":";
                        temp = this.getSeconds();
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp; break;               
                    case "t":
                        temp = this.getHours();
                        if ( temp == 0 || temp > 12 ) temp -= 12;
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp + ":";
                        temp = this.getMinutes();
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp + ":";
                        temp = this.getSeconds();
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp + " ";
                        result += ( this.getHours() < 12 ) ? "AM" : "PM"; break;
                    case "w":
                        result += dow[ this.getDay() ]; break;
                    case "W":
                        result += DOW[ this.getDay() ]; break;
                    case "y": 
                        result += ( "" + this.getFullYear() ).substring(2); break;
                    case "Y":
                        result += this.getFullYear(); break;
                    default:
                        result += char;
                } // end of switch
    
            } // end of else
            ++cnum;
    
        } // end of loop
    
        return result;
    }
    
    function testit( withWhat, utcflag )
    {
        var tick = new Date();
        document.write( "current date/time formatted via '" + withWhat + "' is " 
                        + '<span style="color: red">' + tick.format( withWhat, utcflag ) + "</span><hr/>\n" );
    }
    
    testit( null );
    testit( "LOCAL time is %T" );
    testit( "UTC time is %T", true );
    testit( "Right now it is %t on %B %D, %Y!" );
    testit( "Right now UTC it is %t on %B %D, %Y!", true );
    testit( "Short UK date: %d/%m/%y" );
    testit( "Short USA date: %m/%d/%y" );
    testit( "Time %h:%n%:%s %p" );
    testit( "showing short month and week day: %w, %b %d, %Y");
    </script>
    </body>
    </html>
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #10
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,650
    Thanks
    80
    Thanked 4,638 Times in 4,600 Posts
    Ahhh...a sort of bug in that code: If you pass true for "useUTC" then I change the time of the current object.

    I really shouldn't do that. I should clone the current object, change the clone if needed, and then use the clone throughout the rest of the code. A trivial change. Will make it if anyone cares.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #11
    Regular Coder
    Join Date
    Sep 2002
    Posts
    462
    Thanks
    0
    Thanked 20 Times in 20 Posts
    First, thanks glenngv and Old Pedant for all your help!

    Now to the other stuff...heheh.
    if the order and meaning of a given position is fixed (e.g., in this case arguments[2] is always language), then why bother?
    Just playin around.

    else {
    ... not clear what your intent is here with custom array passed in ...
    }
    The larger array is strictly for default purposes, using a custom array allows for faster processing of less items and will eventually allow custom arrays to be passed directly into function from another without using a global array. Where I can see he value in your example, it currently has no value to mine unless I can access the custom array 'availableValues' without doing a search loop to find it. Looks perty though...hehehe.

    you can avoid all the eval() crud on the stuff based on language
    See that I might be able to use! Languages was just an option I came up with and wasn't exactly sure about using. I've seen this type of coding in various scripts but wasn't sure how it worked. Thanks for that! Made some notes...heheh

    p.s.: Your date suffixes isn't really complete, at all. For example, Russian adjectival suffixes have to agree with the GENDER of the thing they are modifying, not just the number per se. I'm pretty sure other languages do that, too.
    Noted but at this stage useless info. I do not know how other languages use things because I only speak one. Again language was an option and at this point in script developement no a neccessity. At this point in the game it's all an "Internet Scavenger Hunt" trying to find working codes to make modifications, since most javascript sites do not go into depth on the date object. Plus I find new ways to work with this function.

    I know I shouldn't do this, but I had to give it a shot.
    My simple-minded version of date formatting:
    Why shouldn't you do it?
    Why is it so simple minded when you declare the abreviated dow,moy and the suf for each day. Anyway I'll check it out an see what happens.

    Thanks again guys for the help will study more an see what happens.
    NO Limits!! DHCreationStation.com
    ------------------------------------------------------------
    For projects using MediaTypes (MIMETypes) visit E-BAM.net -(updated weekly)

    Broken items wanted for tinkerin'! PostItNow@BrokenEquipment.com
    Global Complaint Dept.

  • #12
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,650
    Thanks
    80
    Thanked 4,638 Times in 4,600 Posts
    Couldn't help myself. Here it is, showing use of languages. I have no idea what the appropriate suffixes are for Spanish or French. So, if suffixes aren't given, I supply blank ones by default.

    Code:
    <html>
    <body>
    <script type="text/javascript">
    /*
     * Date.format( )  
     *
     * Alters the Date object prototype to provide a method
     * that parallels MySQLs FORMAT_DATE function.
     * 
     * There are some important differences in the designators, so watch out.
     * 
     * AVAILABLE FORMAT SPECIFIERS:
    
    %a 	Numeric day of the week (0=Sunday..6=Saturday)
    %A 	Numeric day of the week (0=Monday..6=Sunday)
    
    %b 	Abbreviated month name (Jan..Dec)
    %B 	Month name (January..December)
    
    %d 	Day of the month, numeric (01..31)
    %D 	Day of the month with suffix (1st, 2nd, 3rd, …)
    
    %h 	Hour (01..12)
    %H 	Hour (00..23)
    
    %j 	Day of year (001..366)
    
    %M,%m 	Month, numeric (01..12)
    %N,%n 	Minutes, numeric (00..59)
    
    %P 	AM or PM
    %p 	am or pm
    
    %S,%s 	Seconds (00..59)
    
    %T 	Time, 24-hour (hh:mm:ss)
    %t 	Time, 12-hour (hh:mm:ss followed by AM or PM)
    
    %w 	Abbreviated weekday name (Sun..Sat)
    %W 	Weekday name (Sunday..Saturday)
    
    %y 	Year, numeric (two digits)
    %Y 	Year, numeric, four digits
    
    %% 	A literal “%” character
     
     *
     *******************************************************
     */
    
    Date.prototype.format = function(formatString,useUTC,language) 
    {
        if ( formatString == null ) formatString = "%W, %B %d, %Y"; // change default as you wish!
        if ( useUTC == null ) useUTC = false; // change default as you wish!
        if ( language == null ) language = "EN"; // change default as you wish
    
        var theDate = new Date(this.getTime());
    
        var languages = {
            "EN" : {
                 DOW : ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],
                 dow : ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],
                 MOY : ["January","February","March","April","May","June","August",
                        "September","October","November","December" ],
                 moy : ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],
                 suf : ["st","nd","rd","th","th","th","th","th","th","th",
                        "th","th","th","th","th","th","th","th","th","th",
                        "st","nd","rd","th","th","th","th","th","th","th",
                        "st"]
            },
            "ES" : {
                 DOW : ["Domingo","Lunes","Martes","Miércoles","Jueves","Viernes","Sábado"],
                 dow : ["Dom","Lun","Mar","Mié","Jue","Vie","Sáb"],
                 MOY : ["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto",
                        "Septiembre","Octubre","Noviembre","Diciembre"],
                 moy : ["Ene","Feb","Mar","Abr","May","Jun","Jul","Ago","Sep","Oct","Nov","Dic"]
            },
            "FR" : {
                 DOW : ["Dimanche","Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi"],
                 dow : ["Dim.","Lun.","Mar.","Mer.","Jeu.","Ven.","Sam."],
                 MOY : ["Janvier","Février","Mars","Avril","Mai","Juin","Juillet",
                        "Août","Septembre","Octobre","Novembre","Décembre"],
                 moy : ["Janv.","Févr.","Mars","Avr.","Mai","Juin",
                        "Juil.","Août","Sept.","Oct.","Nov.","Déc."]
            }
        };
        var useLanguage = languages[language];
        var DOW = useLanguage["DOW"];
        var dow = useLanguage["dow"];
        var MOY = useLanguage["MOY"];
        var moy = useLanguage["moy"];
        var suf = useLanguage["suf"];
        if ( suf == null ) 
        {
            suf = [];
            for ( var d = 1; d <= 31; ++d ) suf.push("");
        }
    
        var result = "";
    
        if ( useUTC ) {
            theDate.setTime( theDate.getTime() + theDate.getTimezoneOffset() * 60000 );
        }
    
        var cnum = 0;
        var temp;
        while ( cnum < formatString.length )
        {
            var char = formatString.charAt(cnum);
            if ( char != "%" )
            {
                result += char; 
            } else {
                ++cnum;
                var char = formatString.charAt(cnum);
                switch ( char )
                {
                    case "a":
                        result += theDate.getDay(); break;
                    case "A": 
                        result += ( 6 + theDate.getDay() ) % 7; break;
                    case "b":
                        result += moy[ theDate.getMonth() ]; break;
                    case "B":
                        result += MOY[ theDate.getMonth() ]; break;
                    case "d":
                        temp = theDate.getDate();
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp; break;               
                    case "D":
                        temp = theDate.getDate();
                        result += temp + suf[temp-1]; break;
                    case "h":
                        temp = theDate.getHours();
                        if ( temp == 0 || temp > 12 ) temp -= 12;
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp; break;               
                    case "H":
                        temp = theDate.getHours();
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp; break;               
                    case "m": case "M":
                        temp = 1 + theDate.getMonth();
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp; break;               
                    case "n": case "N":
                        temp = theDate.getMinutes();
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp; break;               
    		case "p": 
                        result += ( theDate.getHours() < 12 ) ? "am" : "pm"; break;
    		case "P": 
                        result += ( theDate.getHours() < 12 ) ? "AM" : "PM"; break;
                    case "s": case "S":
                        temp = theDate.getSeconds();
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp; break;               
                    case "T":
                        temp = theDate.getHours();
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp + ":";
                        temp = theDate.getMinutes();
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp + ":";
                        temp = theDate.getSeconds();
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp; break;               
                    case "t":
                        temp = theDate.getHours();
                        if ( temp == 0 || temp > 12 ) temp -= 12;
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp + ":";
                        temp = theDate.getMinutes();
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp + ":";
                        temp = theDate.getSeconds();
                        result += ( ( temp < 10 ) ? "0" : "" ) + temp + " ";
                        result += ( theDate.getHours() < 12 ) ? "AM" : "PM"; break;
                    case "w":
                        result += dow[ theDate.getDay() ]; break;
                    case "W":
                        result += DOW[ theDate.getDay() ]; break;
                    case "y": 
                        result += ( "" + theDate.getFullYear() ).substring(2); break;
                    case "Y":
                        result += theDate.getFullYear(); break;
                    default:
                        result += char;
                } // end of switch
    
            } // end of else
            ++cnum;
    
        } // end of loop
    
        return result;
    }
    
    function testit( withWhat, utcflag, lang )
    {
        var tick = new Date();
        document.write( "current date/time formatted via '" + withWhat + "' is " 
                        + '<span style="color: red">' + tick.format( withWhat, utcflag, lang ) + "</span><hr/>\n" );
    }
    
    testit( null );
    testit( "LOCAL time is %T" );
    testit( "UTC time is %T", true );
    testit( "Right now it is %t on %B %D, %Y!" );
    testit( "Right now UTC it is %t on %B %D, %Y!", true );
    testit( "Short UK date: %d/%m/%y" );
    testit( "Short USA date: %m/%d/%y" );
    testit( "Time %h:%n%:%s %p" );
    testit( "showing short month and week day: %w, %b %d, %Y");
    document.write("Now in Spanish:<hr>");
    testit( null,null,"ES" );
    testit( "Right now it is %T on %B %D, %Y!",null,"ES" );
    testit( "Right now UTC it is %T on %B %D, %Y!", true, "ES" );
    testit( "showing short month and week day: %w, %b %d, %Y",null,"ES");
    document.write("Now in French:<hr>");
    testit( null,null,"FR" );
    testit( "Right now it is %T on %B %D, %Y!",null,"FR" );
    testit( "Right now UTC it is %T on %B %D, %Y!", true, "FR" );
    testit( "showing short month and week day: %w, %b %d, %Y",null,"FR");
    
    </script>
    </body>
    </html>
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

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