Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Page History: Date Formatting - JavaScript

Compare Page Revisions



« Older Revision - Back to Page History - Newer Revision »


Page Revision: Wed, Sep 07, 2011, 11:37 AM


Overview

Dates are notoriously difficult to work with in JavaScript. This article outlines how create a JavaScript Date object from a JSON object acquired via an AJAX call, and formats the date using the familiar .NET formatting codes.

Sample Usage

Controller Code

public class MyController : Controller
{
    [HttpPost]
    public JsonResult GetData()
    {
        var item = new { MyDate = DateTime.Now, Message = "Hello world" }
        return Json(item);
    }
}

JavaScript Code

After the following code runs, the page element with ID "myDate" will contain the current date, e.g., "September 2011".

$.ajax({
    type: 'post',
    url: '/MyController/GetData',
    datatype:'json',
    success: function(data){

        var myDate = Date.fromJsonDate(data.MyDate).toFormat("MMMM yyyy");
        $('#myDate').html(myDate);

    }

Reusable JavaScript Code

/*===============================================================================================*/
Date.fromJsonDate = function (input) {
    ds = input.substr(6, input.length - 8) * 1;
    return new Date(ds);
}
/*===============================================================================================*/
Date.prototype.getMonthName = function () {

    var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
		'September', 'October', 'November', 'December'];

    return monthNames[this.getMonth()];

}
/*===============================================================================================*/
Date.prototype.toFormat = function (formatCode) {

    var MMMM = this.getMonthName();
    var MMM = MMMM.substr(0, 3);
    var M = this.getMonth() + 1;
    var MM = (M < 10 ? "0" : "") + M;
    var d = this.getDate();
    var dd = (d < 10 ? "0" : "") + d;
    var yyyy = this.getFullYear();
    var yy = (yyyy + "").substr(2, 2);

    var result = formatCode;
    result = result.replace("MMMM", MMMM);
    result = result.replace("MMM", MMM);
    result = result.replace("MM", MM);
    result = result.replace("M", M);
    result = result.replace("dd", dd);
    result = result.replace("d", d);
    result = result.replace("yyyy", yyyy);
    result = result.replace("yy", yy);
    return result;

}
/*===============================================================================================*/

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.