Parse DateTime string in JavaScript
Asked Answered
S

9

95

Does anyone know how to parse date string in required format dd.mm.yyyy?

Shipmate answered 16/10, 2009 at 8:14 Comment(1)
Do you want to create a new date object from a string in that format?Johnnajohnnie
C
139

See:

Code:

var strDate = "03.09.1979";
var dateParts = strDate.split(".");

var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
Cuenca answered 16/10, 2009 at 8:19 Comment(5)
mmm, but how to check strDate has a invalid value like "30.30.2000"?Guncotton
@user674887, you could compare the values after parsing. e.g. dateParts[1]-1 == date.getMonth()Cuenca
If you have date both TIME like this: "2014-05-20T16:43:56.71-06:00" var partesFecha = solicitud.CreatedDate.split("T")[0].split("-"); var createdDate = new Date(partesFecha[0], (partesFecha[1] - 1), partesFecha[2]); First extract date before T and later split year, month and day.Yingyingkow
can't believe you have to use a split to get the expected date format in javascriptPlumbic
Anyone else find it odd that the Mozilla reference article on the Date object itself says "Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies."?Broughton
D
51

If you are using jQuery UI, you can format any date with:

<html>
    <body>
        Your date formated: <span id="date1"></span><br/>
    </body>
</html>

 

var myDate = '30.11.2011';
var parsedDate = $.datepicker.parseDate('dd.mm.yy', myDate);

$('#date1').text($.datepicker.formatDate('M d, yy', parsedDate));

http://jsfiddle.net/mescalito2345/ND2Qg/14/

Dippold answered 25/4, 2011 at 20:11 Comment(2)
+1 I don't see as being totally out of scope, JavaScript and JQuery are a common combination.Chessa
An answer shouldn't rely on a library that isn't tagged or mentioned in the OP. Using jQuery as a date library is massive overkill when a 3 line function can do the same job.Invasion
S
9

We use this code to check if the string is a valid date

var dt = new Date(txtDate.value)
if (isNaN(dt))
Soutor answered 16/10, 2009 at 8:16 Comment(2)
the given format does not match the format required by developer.mozilla.org/en/Core_JavaScript_1.5_Reference/… (and thus that Date constructor will not suffice)Cuenca
That doesn't test for valid dates at all, it just tests if the Date constructor can make a valid date from the input. The two aren't the same thing.Invasion
S
7

refs: http://momentjs.com/docs/#/parsing/string/

If you use moment.js, you can use "string" + "format" mode

moment(String, String);
moment(String, String, String);
moment(String, String, Boolean);
moment(String, String, String, Boolean);

ex:

moment("12-25-1995", "MM-DD-YYYY");
Saxecoburggotha answered 30/9, 2014 at 6:52 Comment(1)
For most cases, MomentJS is an overkill, as using pure JavaScript just requires hundreds of bytes, while MomentJS is 12.4kb gzipped. Convenient for developers but slows down the website. Doesn't worth.Intestine
P
3

I'v been used following code in IE. (IE8 compatible)

var dString = "2013.2.4";
var myDate = new Date( dString.replace(/(\d+)\.(\d+)\.(\d+)/,"$2/$3/$1") );
alert( "my date:"+ myDate );
Plataea answered 10/10, 2014 at 2:52 Comment(0)
P
2

ASP.NET developers have the choice of this handy built-in (MS JS must be included in page):

var date = Date.parseLocale('20-Mar-2012', 'dd-MMM-yyyy');

http://msdn.microsoft.com/en-us/library/bb397521%28v=vs.100%29.aspx

Portuna answered 10/4, 2012 at 8:6 Comment(1)
OP does not mention he uses ASP.NETIntestine
P
2

Use Date object:

var time = Date.parse('02.02.1999');
document.writeln(time);

Give: 917902800000

Prodigal answered 23/8, 2012 at 15:30 Comment(4)
new Date(Date.parse('02.02.1999'))Sturrock
+1 For Duke comments on new Date(Date.parse('02.02.1999')) for JavascriptDiscoid
Returns NaN in at least two current browsers. See Why does Date.parse give incorrect results?Invasion
@Duke— new Date(Date.parse('02.02.1999')) will produce identical results to new Date('02.02.1999'), including Invalid Date in some browsers. Using the built–in parser is arguably the worst way to parse a timestamp.Invasion
R
2

This function handles also the invalid 29.2.2001 date.

function parseDate(str) {
    var dateParts = str.split(".");
    if (dateParts.length != 3)
        return null;
    var year = dateParts[2];
    var month = dateParts[1];
    var day = dateParts[0];

    if (isNaN(day) || isNaN(month) || isNaN(year))
        return null;

    var result = new Date(year, (month - 1), day);
    if (result == null)
        return null;
    if (result.getDate() != day)
        return null;
    if (result.getMonth() != (month - 1))
        return null;
    if (result.getFullYear() != year)
        return null;

    return result;
}
Revolutionary answered 31/3, 2014 at 10:9 Comment(0)
G
0

you can format date just making this type of the code.In javascript.

 // for eg.
              var inputdate=document.getElementById("getdate").value);
                 var datecomp= inputdate.split('.');

                Var Date= new Date(datecomp[2], datecomp[1]-1, datecomp[0]); 
                 //new date( Year,Month,Date)
Gonta answered 20/9, 2017 at 10:53 Comment(4)
You're supposed to use javascript not jquery as there is no jquery tagPiano
happy ... meaning is to just understand the senarioGonta
Well. I don't think your example is any different than the one given by Martin Staufcik. In fact his answer has additional logic to handle invalid dates.Piano
Martin Staufcik handle those conditions which does not occurs generally. can you give me any calendar which can give invalidates.why we should write so long code when we can handle in short way. It would me much better if Martin Staufcik also give to handle date with time to handle.Gonta

© 2022 - 2024 — McMap. All rights reserved.