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)
- //Line to write in page load event given below:
- Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "DateFormat", "var dateFormat ='" + Session["DateFormat"] + "'", true);
- // JavaScript function
- function ParseDate(dateString) {
- //Date string must contain the back slash.
- // Split the date string, generated array length should be more than three
- dateParts = dateString.split("/");
- if (dateParts.length != 3)
- return undefined;
- else {
- var ReturnDate = new Date();
- //check the date format and set the date in defined culture
- if (dateFormat == "d/M/yyyy") {
- ReturnDate.setMonth(dateParts[1] - 1, dateParts[0]);
- } else {
- ReturnDate.setMonth(dateParts[0] - 1, dateParts[1]);
- }
- ReturnDate.setFullYear(y2k(dateParts[2]));
- ReturnDate.setHours(0);
- ReturnDate.setMinutes(0);
- ReturnDate.setSeconds(0);
- ReturnDate.setMilliseconds(0);
- return ReturnDate;
- }
- }
- //JavaScript function to check the year string
- function y2k(yearString) {
- //Check the year string
- if (yearString.length == 4) {
- return yearString;
- } else if (yearString.length == 2) {
- var year = Number(yearString);
- if (year < 50) {
- year = year + 2000;
- } else {
- year = year + 1900;
- }
- return year;
- } else {
- return 0;
- }
- }

Join the conversation! Your thoughts help the community grow.