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. function ParseDate(dateString) {
  5. //Date string must contain the back slash.
  6. // Split the date string, generated array length should be more than three
  7. dateParts = dateString.split("/");
  8. if (dateParts.length != 3)
  9. return undefined;
  10. else {
  11. var ReturnDate = new Date();
  12. //check the date format and set the date in defined culture
  13. if (dateFormat == "d/M/yyyy") {
  14. ReturnDate.setMonth(dateParts[1] - 1, dateParts[0]);
  15. } else {
  16. ReturnDate.setMonth(dateParts[0] - 1, dateParts[1]);
  17. }
  18. ReturnDate.setFullYear(y2k(dateParts[2]));
  19. ReturnDate.setHours(0);
  20. ReturnDate.setMinutes(0);
  21. ReturnDate.setSeconds(0);
  22. ReturnDate.setMilliseconds(0);
  23. return ReturnDate;
  24. }
  25. }
  26. //JavaScript function to check the year string
  27. function y2k(yearString) {
  28. //Check the year string
  29. if (yearString.length == 4) {
  30. return yearString;
  31. } else if (yearString.length == 2) {
  32. var year = Number(yearString);
  33. if (year < 50) {
  34. year = year + 2000;
  35. } else {
  36. year = year + 1900;
  37. }
  38. return year;
  39. } else {
  40. return 0;
  41. }
  42. }