Javascript Date Format

Posted: Friday February 17th, 2012 in Javascript, Project
Tags: ,

Searching the web I could not find a date formatter in javascript that could suit my needs.

What I wanted was a way to parse / format any time trying not to implement all methods in the prototype of the Date object. Also choose freely the template to be used, allowing to write certain variables rather than replace individual letters. I’m used with the SimpleDateFormat class in Java, which gave me great ideas.

At the end achieved the following results, which works as follows:

//By default it has the week names in portuguese, but it is easly manipulated.
//The only problem is the parse, which currently has the BR date format
//Formatting the current date to String
var currDate = new Date();
var dateFormat = new JSDateFormat("Current Date: %d%d/%M%M/%y%y%y%y. Time: %H%H:%m%m:%s%s. The week day is %WEEK");
dateFormat.format(currDate); //Current Date: 17/02/2012. Time: 21:07:20. The week day is Sexta-Feira

//Parsing
var dateFormat = new JSDateFormat();
dateFormat.getDateObj("15/05/2012 15:33:45"); //return the Date Object with the given time set

The method format() is free for any kind of string (since avoided the use of “%”):

/**
* %d - Day of Month (01, 02...20,21)
* %M - Month of Year (03, 04...11, 12)
* %y - Year (001990, 02008, 2009, 009, 09, 9)
* %h - Time AM/PM (00, 01...11, 12)
* %H - Day Time (00, 01...17, 18)
* %m - Minutes in Hour (05, 06...50, 51...59, 60)
* %s - Seconds in minutes (05, 06...50, 51...59, 60)
* %a - Return the post/ante meridiem (AM, PM)
* %WEEK - Day of week (Domingo, Segunda-Feira...Sexta-Feira, Sábado)
*/

THe only method that is kind of restrict is the getDateObj() which only make the parse of pre-defined strings:

/**
* Date:
* xx/xx/xxxx - day/month/year
* xx-xx-xxxx - day-month-year
* Time:
* xx:xx - hour:minute
* xx:xx:xx - hour:minute:second
* Date/Time:
* xx/xx/xxxx xx:xx:xx
* xx/xx/xxxx xx:xx
* xx-xx-xxxx xx:xx:xx
* xx-xx-xxxx xx:xx
*/

Questions/Sugestions?

To download click here

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>