Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating Date Time In Javascript

I need some help with validating a date time string in Javascript, based on the browser's language.

I can get the datetime format easily enough, for instance if the language is set to pt-BR the format would be

dd/MM/yyyy HH:mm:ss

I tried using something like this:

var dateFormat = "dd/MM/yyyy HH:mm:ss";
var x = Date.parseExact($("#theDate").val(), dateFormat);

However x is always Null. I am thinking because Date.parseExact is not able to do times. I need to be able to do this for all browser languages and I would prefer to not use another library. Using Regex is out also since I would need to write so many different expressions.

Does anyone have any suggestions to help me ge on the right track? I am also not against using a webmethod.

I have tried using the following webmethod, which works with en-US but nothing else:

Public Function ValidateDates(ByVal strDate_In As String) As String
    Dim theFormat As String = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern() + " " + CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern()
    Try
        Dim d As DateTime = DateTime.ParseExact(strDate_In, theFormat, CultureInfo.CurrentCulture)
        Return "true"
    Catch ex As Exception
       Return "false"
    End Try
End Function
like image 723
NiteTrip Avatar asked May 07 '15 14:05

NiteTrip


People also ask

Is valid date format JavaScript?

mm/dd/yyyy or mm-dd-yyyy format. In the following examples, a JavaScript function is used to check a valid date format against a regular expression. Later we take each part of the string supplied by user (i.e. dd, mm and yyyy) and check whether dd is a valid date, mm is a valid month or yyyy is a valid year.

Can JavaScript handle dates and time?

The date and time is broken up and printed in a way that we can understand as humans. JavaScript, however, understands the date based on a timestamp derived from Unix time, which is a value consisting of the number of milliseconds that have passed since midnight on January 1st, 1970.


1 Answers

You can use Regex to do this:

var dateFormat = "dd/MM/yyyy HH:mm:ss";
var x = $("#theDate").val().match(/^(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2}):(\d{2})$/);
console.log(x);

Demo: https://jsfiddle.net/kzzn6ac5/

update The following regex may help you and improve it according to your need:

^((\d{2}|\d{4})[\/|\.|-](\d{2})[\/|\.|-](\d{4}|\d{2}) (\d{2}):(\d{2}):(\d{2}))$

It matches the following format with /.- and yyyy/mm/dd hh:mm:ss or dd/mm/yyyy hh:mm:ss

Updated demo: https://jsfiddle.net/kzzn6ac5/1 or https://regex101.com/r/aT1oL6/1

Further Regex expressions relevant to date matching can be found here.

like image 85
Radonirina Maminiaina Avatar answered Oct 05 '22 21:10

Radonirina Maminiaina