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 5 of 5
  1. #1
    Senior Coder
    Join Date
    Aug 2002
    Posts
    3,467
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Custom date object with PHP-like text-parsed output

    Well, this is acutally a couple different scripts. First is the custom date object myDate which retrieves pretty much every value that you'd need from a date and sets it as a property. If no argument is supplied, the current time and date is used. If you do supply an argument, you can send an existing javascript Date object, or a string that is compatible with declaring a normal javascript Date object.

    The 2nd part of this script is the method getDate (and some accompanying String methods) that allow you to retrieve the date as a string by passing it a format string just like the PHP date() function accepts. The code posted below includes sufficient (I think) examples to help you understand what is going on. You will notice that I didn't duplicate EVERY code over from PHP, and a few are slightly different. Those that I left out I felt weren't very necessary, or I didn't feel like doing the algorithm for them .

    Both myDateObj.getDate() and PHP's date() allow you to include text into the string that you don't want parsed, but each handles it differently. In PHP, you need to escape characters normally with a backslash. For getDate you need to proceed each character with a pipe "|". So, instead of
    PHP Code:
    $dateStr date("\\D\\a\\y z"); 
    as it would be in PHP, you would use
    Code:
    var d = new myDate();
    var dateStr = d.getDate("D|a|y| z");
    There are more examples of how this works below.

    Note: There is also a nice arrayReplace() method for strings that is handy for doing multiple replace() operations all at once, so I guess this is really like 3 handy scripts

    Any comments, problems, improvements are welcome.
    Code:
    <html>
    <head>
    <title>test</title>
    <meta http-equiv="expires" content="0">
    <script type="text/javascript">
    
    /*** First Part of Script, the custom date object ***/
    
    function myDate(dateStr) {
    	if (typeof dateStr != 'undefined') {
    		var d = new Date(dateStr);
    		this.dateString = dateStr;
    		}
    	else if (typeof dateStr == 'object')
    		var d = dateStr;
    	else
    		var d = new Date();
    	var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
    	var weekDays = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
    	var monthDays = [31,28,31,30,31,30,31,31,30,31,30,31];
    
    	this.epoch = d.getTime();
    	this.epochS = Math.round(this.epoch / 1000);
    	this.year4 = d.getFullYear();
    	this.year2 = parseInt(this.year4.toString().substring(2));
    	this.leap = (this.year4 % 400 == 0) ? true : (this.year4 % 4 == 0 && this.year4 % 100 != 0) ? true : false;
    	if (this.leap) monthDays[1]++;
    	this.mnth = d.getMonth();
    	this.month = this.mnth + 1;
    	this.month_2 = leadingZero(this.month);
    	this.monthName = months[this.mnth];
    	this.monthNameShort = this.monthName.substring(0,3);
    	this.days = monthDays[this.mnth];
    	this.dy = d.getDay();
    	this.day = this.dy + 1;
    	this.dayName = weekDays[this.dy];
    	this.dayNameShort = this.dayName.substring(0,3);
    	this.date = d.getDate();
    	this.date_2 = leadingZero(this.date);
    	this.suffix = (this.date % 10 == 1 ) ? "st" : (this.date % 10 == 2) ? "nd" : (this.date % 10 == 3) ? "rd" : "th";
    	this.hours24 = d.getHours();
    	this.hours24_2 = leadingZero(this.hours24)
    	this.hours12 = (this.hours24 == 0) ? 12 : (this.hours24 > 12) ? this.hours24-12 : this.hours24;
    	this.hours12_2 = leadingZero(this.hours12);
    	this.minutes = d.getMinutes();
    	this.minutes_2 = leadingZero(this.minutes);
    	this.seconds = d.getSeconds();
    	this.seconds_2 = leadingZero(this.seconds);
    	this.millis = d.getMilliseconds();
    	this.ampm = (this.hours24 == 0) ? "am" : (this.hours24 >= 12) ? "pm" : "am";
    	this.GMTstring = d.toGMTString();
    	this.offset = d.getTimezoneOffset();
    
    	function leadingZero(num) {
    		return (num < 10) ? "0" + num : num.toString();
    		}
    	}
    
    myDate.prototype.getDayOfYear = function() {
    	var total = 0;
    	var monthDays = [31,28,31,30,31,30,31,31,30,31,30,31];
    	if (this.leap) monthDays[1]++;
    	for (var i=0; i<this.mnth; total += monthDays[i++]) {}
    	total += this.date;
    	return total;
    	}
    
    /*** Second part of script, the PHP-like parsed output ***/
    
    myDate.prototype.getDate = function(str) {
    	var p = ['a','A','B','d','D','F','g','G','h','H','i','I','j','l','L','m','M','n','O','r','s','S','t','T','U','w','W','Y','y','z','Z'];
    	var r = new Array();
    	var i = 0;
    	var delChar = "|";
    	var sNull = "null".delimit(delChar)
    	r[i++] = this.ampm.delimit(delChar);
    	r[i++] = this.ampm.toUpperCase().delimit(delChar);
    	r[i++] = sNull;
    	r[i++] = this.date_2;
    	r[i++] = this.dayNameShort.delimit(delChar);
    	r[i++] = this.monthName.delimit(delChar);
    	r[i++] = this.hours12;
    	r[i++] = this.hours24;
    	r[i++] = this.hours12_2;
    	r[i++] = this.hours24_2;
    	r[i++] = this.minutes_2;
    	r[i++] = sNull;
    	r[i++] = this.date;
    	r[i++] = this.dayName.delimit(delChar);
    	r[i++] = (this.leap)?1:0;
    	r[i++] = this.month_2;
    	r[i++] = this.monthNameShort.delimit(delChar);
    	r[i++] = this.month;
    	r[i++] = this.offset;
    	r[i++] = this.GMTstring.delimit(delChar);
    	r[i++] = this.seconds_2;
    	r[i++] = this.suffix.delimit(delChar);
    	r[i++] = this.days;
    	r[i++] = sNull;
    	r[i++] = this.epochS;
    	r[i++] = this.dy;
    	r[i++] = sNull;
    	r[i++] = this.year4;
    	r[i++] = this.year2;
    	r[i++] = this.getDayOfYear();
    	r[i++] = sNull;
    	for (i=0; i<p.length; i++)
    		p[i] = "/" + p[i] + "(?!\\|)/g";
    	return str.arrayReplace(p, r).replace(/\|/g,"");
    	}
    
    String.prototype.arrayReplace = function(arrP, arrR) {
    	var p, s = this;
     	for (var i=0; i<arrP.length; i++) {
    		var flags = arrP[i].substring(arrP[i].lastIndexOf("/")+1);
    		var regex = arrP[i].substring(1,arrP[i].lastIndexOf("/"));
    		p = new RegExp(regex, flags);
    		s = s.replace(p, arrR[i]);
    		}
    	return s;
    	}
    
    String.prototype.delimit = function(char) {
    	var s = "";
    	for (var i=0; i<this.length; i++) {
    		s += this.charAt(i) + char;
    		}
    	return s;
    	}
    
    </script>
    </head>
    
    <body>
    
    <script type="text/javascript">
    
    /*** Example using current date/time ***/
    
    var md1 = new myDate();
    document.write(md1.getDate("l jS of F Y h:i:s A")+"<br>");
    document.write(md1.getDate("T|o|d|a|y| i|s| m.d.y")+"<br>");
    document.write(md1.getDate("D M j G:i:s Y")+"<br>");
    document.write("It " + (md1.leap?"is":"is not") + " a leap year<br>");
    document.write("The unix epoch occurred " + md1.epochS + " seconds ago");
    document.write("<hr>");
    
    /*** Example using javascript Date object as argument ***/
    
    var d1 = new Date(2000, 01, 02, 15, 15, 15);
    var md2 = new myDate(d1);
    document.write(md2.getDate("l jS of F Y h:i:s A")+"<br>");
    document.write(md2.getDate("T|o|d|a|y| i|s| m.d.y")+"<br>");
    document.write(md2.getDate("D M j G:i:s Y")+"<br>");
    document.write("It " + (md2.leap?"is":"is not") + " a leap year<br>");
    document.write("The unix epoch occurred " + md2.epochS + " seconds ago");
    document.write("<hr>");
    
    /*** Example using Date object compatible string as argument ***/
    
    var md3 = new myDate("December 10, 1978 12:23:00");
    document.write(md3.getDate("l jS of F Y h:i:s A")+"<br>");
    document.write(md3.getDate("T|o|d|a|y| i|s| m.d.y")+"<br>");
    document.write(md3.getDate("D M j G:i:s Y")+"<br>");
    document.write("It " + (md3.leap?"is":"is not") + " a leap year<br>");
    document.write("The unix epoch occurred " + md3.epochS + " seconds ago");
    </script>
    </body>
    </html>
    Last edited by beetle; 12-06-2002 at 07:07 PM.
    My Site | fValidate | My Brainbench | MSDN | Gecko | xBrowser DOM | PHP | Ars | PVP
    “Minds are like parachutes. They don't work unless they are open”
    “Maturity is simply knowing when to not be immature”

  • #2
    Senior Coder
    Join Date
    Jun 2002
    Location
    frankfurt, german banana republic
    Posts
    1,848
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Nice!

    Admit it, you used PHP's date() function very often lately, and felt like it's functionality would be desirable in JavaScript.

    I've been at this point some months ago and tried to make *complete* (well as complete as it gets) port of PHPs date function to JavaScript. I implemented it as a custom method of the Date object directly, but... wait, I'll open a separate thread with the script inside.

    Here it is: Port of PHP's date() function to javascript
    Last edited by mordred; 12-07-2002 at 03:24 AM.

  • #3
    Senior Coder
    Join Date
    Aug 2002
    Posts
    3,467
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Yes, I admit it. I like different things about both of our implementations. Well done, mordred.

    Honestly, I can tell you approached this more directly than I did. This actually started when I decided to make the arrayReplace method for strings, and thought, "Hey, I can use this for making that PHP-like date function that I've wanted". And I already had the custom date object made....so I just used them together for this.
    My Site | fValidate | My Brainbench | MSDN | Gecko | xBrowser DOM | PHP | Ars | PVP
    “Minds are like parachutes. They don't work unless they are open”
    “Maturity is simply knowing when to not be immature”

  • #4
    Senior Coder
    Join Date
    Jun 2002
    Location
    frankfurt, german banana republic
    Posts
    1,848
    Thanks
    0
    Thanked 0 Times in 0 Posts
    What I like about your version is it's OOP functionality. Whereas I just iterated over an array out of the format string passed to one method, and pushing everything into a gigantic switch statement, your myDate object consists of a collection of small functions for each formatting instruction. Looks a lot more "designed" than my script.

    And yes, I just thought "I want a date() function in JavaScript just like in PHP, nothing more or less" and consequently set on this path. At least now I know some of the more trickier Date methods a little bit better.

  • #5
    Senior Coder
    Join Date
    Aug 2002
    Posts
    3,467
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks, I've been trying to get better with doing stuff in javascript as OO. To be honest, my favorite part of the script is the arrayReplace method for strings. I have many other uses for that. I just wish I could figure the regular expression syntax that would work opposite the way x(?!y) does, so I could replace only the characters that were preceeded by a backslash. Am I missing some regex syntactical goodie? Since the backslash is already used for many different things in regular expressions, I couldn't quite wrap my head around getting this done.

    psuedo example (fake code in red)

    var str = "\\aa\\a";
    str = str.replace(/(?!\\)a/g,"1").replace(/\\/g,"");
    // str == "a1a";

    But, alas, as we all know, this doesn't work
    My Site | fValidate | My Brainbench | MSDN | Gecko | xBrowser DOM | PHP | Ars | PVP
    “Minds are like parachutes. They don't work unless they are open”
    “Maturity is simply knowing when to not be immature”


  •  

    Posting Permissions

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