[javascript] how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery

Possible Duplicate:
Extending JavaScript's Date.parse to allow for DD/MM/YYYY (non-US formatted dates)?
Convert dd-mm-yyyy string to date

Entered a date in textbox, for example: 05/09/1985, and I wanted to convert it to 05-Sep-1985 (dd-MMM-yyyy) format. How would I achieve this? Note that the source format may be dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format.

Code Snippet:

 function GetDateFormat(controlName) {
        if ($('#' + controlName).val() != "") {      
            var d1 = Date.parse($('#' + controlName).val());
            if (d1 == null) {
                alert('Date Invalid.');
                $('#' + controlName).val("");
            }
                var array = d1.toString('dd-MMM-yyyy');
                $('#' + controlName).val(array);
        }
    }

This code returns 09-May-1985 but I want 05-Sep-1985. Thanks.

This question is related to javascript jquery asp.net date

The answer is


Date.parse recognizes only specific formats, and you don't have the option of telling it what your input format is. In this case it thinks that the input is in the format mm/dd/yyyy, so the result is wrong.

To fix this, you need either to parse the input yourself (e.g. with String.split) and then manually construct a Date object, or use a more full-featured library such as datejs.

Example for manual parsing:

var input = $('#' + controlName).val();
var parts = str.split("/");
var d1 = new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));

Example using date.js:

var input = $('#' + controlName).val();
var d1 = Date.parseExact(input, "d/M/yyyy");

See this http://blog.stevenlevithan.com/archives/date-time-format

you can do anything with date.

file : http://stevenlevithan.com/assets/misc/date.format.js

add this to your html code using script tag and to use you can use it as :

var now = new Date();

now.format("m/dd/yy");
// Returns, e.g., 6/09/07

Try this:

 function GetDateFormat(controlName) {
        if ($('#' + controlName).val() != "") {      
            var d1 = Date.parse($('#' + controlName).val().toString().replace(/([0-9]+)\/([0-9]+)/,'$2/$1'));
            if (d1 == null) {
                alert('Date Invalid.');
                $('#' + controlName).val("");
            }
                var array = d1.toString('dd-MMM-yyyy');
                $('#' + controlName).val(array);
        }
    }

The RegExp replace .replace(/([0-9]+)\/([0-9]+)/,'$2/$1') change day/month position.


Update

Below you've said:

Sorry, i can't predict date format before, it should be like dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format finally i wanted to convert all this format to dd-MMM-yyyy format.

That completely changes the question. It'll be much more complex if you can't control the format. There is nothing built into JavaScript that will let you specify a date format. Officially, the only date format supported by JavaScript is a simplified version of ISO-8601: yyyy-mm-dd, although in practice almost all browsers also support yyyy/mm/dd as well. But other than that, you have to write the code yourself or (and this makes much more sense) use a good library. I'd probably use a library like moment.js or DateJS (although DateJS hasn't been maintained in years).


Original answer:

If the format is always dd/mm/yyyy, then this is trivial:

var parts = str.split("/");
var dt = new Date(parseInt(parts[2], 10),
                  parseInt(parts[1], 10) - 1,
                  parseInt(parts[0], 10));

split splits a string on the given delimiter. Then we use parseInt to convert the strings into numbers, and we use the new Date constructor to build a Date from those parts: The third part will be the year, the second part the month, and the first part the day. Date uses zero-based month numbers, and so we have to subtract one from the month number.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?