DateJS — what should I comment….

On my blog there is a article to introduce how to use date.js which is a powerful lib in the code. And it is a powerful parse date time tool, some of our code segment is like the following.

timercount = 0;

var timeend = new Date(); ;
lasttxtstoptime.value = "";

if (myflag == "theflag") {
    if (lastclickbtn.value == "theValue") {
    timeend = Date.parse(textbox1.value);

However, recently we noticed a very weird bug. When try to parse time like “12:09:21 pm”, it just crashed, so it means this lib can not deal with the noon time with this format (just all time starting with 12:  and end with pm). I did some research and got the root reason. Please see below.

“Date JS was started by Geoffrey McGill in 2007, he abandoned it on May 13th 2008; leaving the Google Code repository stagnant and with many bugs unresolved.

This fork was started improve and maintain DateJS. To keep what is still the most full featured JavaScript Date library alive, maintained, and improved. Currently we’re on track towards a 1.0 release – having fixed almost all the existing bugs and added several new features, improved parsing, and many other changes.”

I just want to say big thanks to those people who still working on this project and would like show my sincerely respects to you guys!  However, maybe no comments to “Geoffrey McGill”, who starting this project and put his uncompleted code with all bugs on the datejs official website. It is very confused for people who looked for the similar libs as when you search from google, the first result returned is his unmaintained “official” website.

The latest code and great version still under maintenance by those fantastic programmers could be found at github as below.


How to use cookie

In web application, sometimes, you have to use cookie no matter client cookie or server cookie to store values you want to save. I summarised as below.

Usage 1: Create per cookie per value
Initialize cookie:
HttpCookie cookie = new HttpCookie(“UserName”);
cookie.Value = “admin”;
Response.AppendCookie(cookie );

Retrieve cookie:
HttpCookie cookie = Request.Cookies(“UserName”);
cookieValue = cookie.Value;
Response.AppendCookie(cookie );

If add cookie from server side:
Response.Cookies.Add(new HttpCookie(“UserName”, “admin”)); //add particular cookie into cookie colliections
Retrieve cookie:
cookieValue = Response.Cookies[“UserName”].Value;

Usage 2: Add all values to one cookie object

HttpCookie cookie = Request.Cookies(“Default”);
cookie.Values.Add(“userid”, “1”); || cookie[“userid”] = “1”; //both syntax work
cookie.Values.Add(“username”, “admin”);

HttpCookie cookie = Request.Cookies(“Default”);
cookieValue = cookie.Values[“userid”];

Basic cookie operations: (create, add value, retrieve and delete)

1. js store cookie

<script type="javascript">
function setCookie(name,value){ //name is cookie's name, value is name's value
         var days = 10; //stored days and can passed by parameters
         var expires = new Date(); //create date variable
         expires.setTime(expires.getTime() + days * 30 * 24 * 60 * 60 * 1000); //expires time = current time + expired time (seconds)
         var str = name + '=' + value +';expires=' + expires.toGMTString(); //store value and expire date time to the cookie(need GMT format to display date string)
         var str = name + '=' + escape(value) +’;expires=’ + expires.toGMTString();                  document.cookie = str; }

The following is the generic cookie

<script type="text/javascript" language="JavaScript">//
function addCookie(name,value,expireHours){
           var cookieString=name+"="+escape(value);
           if(expireHours>0){ //check if setup the date time
           var date=new Date(); 
           cookieString=cookieString+"; expire="+date.toGMTString(); 

Notes: Should use escape() function to encode, it could encode special characters to HEX, such as space will compiled to “20%” and able to save into cookie, nevertheless, it could avoid issues in multiple language environment
document.cookie=”str=”+escape(“I love js”);
after encode:
But after encode by escape(), the value needs to revoke unescape()to decode and retrieve the original cookie value

2. js retrieve cookie value

a.general loop characters retrieve

function getCookie(name){
var strcookie = document.cookie;// get cookie string
var arr = strcookie.split(‘;’); //split cookie
for(var i = 0;i&lt;arr.length;i++){
var arrStr = arr.split(‘=’); //split specific cookie
if(arrStr[0] == name) return arrStr[1]; //check if cookie name existing and output
return "";

b.use unescape to get cookie value

function getCookie(name){
var _password = document.getElementById(‘password’);
var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)")); //use regular expression to get cookie to be a name array
return unescape(arr[2]); //
return ”;

3. delete cookie

<script type="text/javascript" language="JavaScript">
function deleteCookie(name){
            var date=new Date();
            document.cookie=name+"=v; expire="+date.toGMTString();  }  

the more details of cookie usage could be referenced by

Javascript Date lib

Just found a really good javascript date library, which almost meet our daily date operations.

The following is the user manual and you can download the js file from

Step #1 – Pick your weapon

In order to move safely through the shadowy world of the JavaScript Date Class you must add the date.js file to your arsenal of tools.

You can download the latest release from or connect directly to the SVN source repository via

The date.js file can be found within the /build/ folder.

Datejs has traveled to many lands and returns with knowledge of over 150 individual Cultures. Supporting your language of choice is simple, just swap out the date.js file for another culture-specific file.

en-US [English (United States)]
en-US [English (United States)]
de-DE [German (Germany)]
fr-FR [French (France)]

All 150+ CultureInfo files have been pre-compiled and are available within the same /build/ folder as date.js. Each culture file includes translations for many of the strings used in the Datejs library. Some strings have not been translated, although will be filled in over time as the community contributes.

Step #2 – Start your training

The Datejs library includes many helpful functions for easing the pain of developing with Dates and Times in JavaScript. Once the date.js file has been included into your page you can begin some serious training.

If you have not already done so, we highly recommend installing FireBug for FireFox. Among many things, Firebug allows you to execute custom JavaScript code directly in the browser without having to edit your source page — kind of like a command-line for JavaScript. Get it now. The Ninja waits.
Let’s Get Started

Before diving deep into the library, let’s first limber up with some stretching. Exploring the natural language syntax is a good place to start.

// Get today’s date;

// Add 5 days to today;

// Get Friday of this week

// Get March of this year

// Is today Friday?; // true|false

// What day is it?;

Everything ok? A little out of breath? Soooo sorry.

Now, some Date Assassin exercises.

// Get the first Monday of the year

// Get the last Friday of the year

// Set a date to the 15th of the current month at 4:30 PM,
// then add 90 days and make sure that date is a weekday,
// else move to the next weekday.
var d1 =
.set({ day: 15, hour: 16, minute: 30 })
.add({ days: 90 })
if (!d1.isWeekday()) {;

How about letting your users enter a few dates? Say into an field or date picker? Included with the Datejs library is a powerful replacement for the native JavaScript Date parser.

The following examples all start with a String value that we convert into a Date object.

// Lets start simple. “Today”

// How about tomorrow?

// July 8?
Date.parse(‘July 8’);

// With a year?
Date.parse(‘July 8th, 2007’);

// And time?
Date.parse(‘July 8th, 2007, 10:30 PM’);

// Get the date, move to Monday (if not already Monday),
// then alert the date to the user in a different format.
var d1 = Date.parse(‘8-Jul-2007’);
if (! {
alert(d1.toString(‘dddd, MMMM d, yyyy’));

The library also includes some Number fun. In order to execute functions directly on JavaScript Number objects, the number must be wrapped in parentheses. This is a requirement of JavaScript. If the number is declared first, the parentheses are not required.

// Get a date 3 days from now

// 6 month ago

// 12 weeks from now
var n = 12;

// Get a date 30 days after a user supplied date
var d1 = Date.parse(‘07.15.2007’);
var d2 = (30).days().after(d1);

Javascript integreted with GridView rowdatabound event

Javascript code is as below. The second hightlighten part also shows how to set a value to the label, if you just use property “value”, it won’t work.

function CheckGridList(maxnumber, currentcheckboxid){
  var count = 0;
  var leftitems = 0;
  for (i=0; i < document.forms[0].elements.length; i++){           
     if (document.forms[0].elements[i].type == 'checkbox') 
        if (document.forms[0].elements[i].checked == true){                                   
            if (count > maxnumber){
        //document.forms[0].elements[i].checked = false;                                               
            document.getElementById(currentcheckboxid).checked = false;                       
  if (count > maxnumber)
      alert("Only 5 items can be selected at one time.");
      return false;
   else {
         //leftitems = maxnumber - count;
         document.getElementById("lbl_alert").innerHTML = (maxnumber - count).toString() + " items remaining for selecting.";
         return true;

The first highlight get parameter from the function argument currentcheckboxid, but how to pass the current check box client id to the javascript?

Private Sub gridview_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridview.RowDataBound
        Dim ck As CheckBox
            If e.Row.RowType = DataControlRowType.DataRow Then
                ck = DirectCast(e.Row.FindControl("ckselected"), CheckBox)
                ck.Attributes.Add("OnClick", "CheckGridList(" & SurveyController.getMaxItemNumber & ", '" & ck.ClientID & "')")
            End If
        Catch ex As Exception

        End Try
    End Sub

Be cautious the single quote and double quote using, if you just give the id value without single quote, the javascript will pass an object as the parameter instead of the id value.