How to Format Date in Defined Culture in JavaScript

Introduction

 
User face problem format the date string in a particular culture in JavaScript. So, in this blog, I will tell you how to format the date string in JavaScript.
 
In page load event of page
 
Defined the JavaScript variable dateFormat.
 
Variable dateFormat contain the culture (In which format user want to show date)
  1. //Line to write in page load event given below:  
  2. Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "DateFormat""var dateFormat ='" + Session["DateFormat"] + "'"true);  
  3. // JavaScript function  
  4.   
  5. function ParseDate(dateString) {  
  6.     //Date string must contain the back slash.  
  7.     // Split the date string, generated array length should be more than three  
  8.     dateParts = dateString.split("/");  
  9.     if (dateParts.length != 3)  
  10.         return undefined;  
  11.     else {  
  12.         var ReturnDate = new Date();  
  13.         //check the date format and set the date in defined culture  
  14.         if (dateFormat == "d/M/yyyy") {  
  15.             ReturnDate.setMonth(dateParts[1] - 1, dateParts[0]);  
  16.         } else {  
  17.             ReturnDate.setMonth(dateParts[0] - 1, dateParts[1]);  
  18.         }  
  19.   
  20.         ReturnDate.setFullYear(y2k(dateParts[2]));  
  21.         ReturnDate.setHours(0);  
  22.         ReturnDate.setMinutes(0);  
  23.         ReturnDate.setSeconds(0);  
  24.         ReturnDate.setMilliseconds(0);  
  25.         return ReturnDate;  
  26.     }  
  27. }  
  28.   
  29. //JavaScript function to check the year string  
  30.   
  31. function y2k(yearString) {  
  32.     //Check the year string  
  33.     if (yearString.length == 4) {  
  34.         return yearString;  
  35.     } else if (yearString.length == 2) {  
  36.         var year = Number(yearString);  
  37.         if (year < 50) {  
  38.             year = year + 2000;  
  39.         } else {  
  40.             year = year + 1900;  
  41.         }  
  42.         return year;  
  43.     } else {  
  44.         return 0;  
  45.     }