Check Date in Javascript

I need help checking the date string of a date in Javascript based on browser language.

I can get the datetime format quite easily, for example, if the language is set to pt-BR, the format will 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 think because Date.parseExact cannot do times. I need to do this for all browser languages, and I would prefer not to use another library. There is no use of Regex, since I need to write so many different expressions.

Does anyone have any suggestions to help me find the right path? I also do not mind using the web method.

I tried using the following web method that works with en-US, but nothing more:

 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 
+7
javascript
source share
2 answers

You can use Regex for 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 regular expression can help you and improve it according to your needs:

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

It corresponds to 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

Additional regular expression expressions related to date matching can be found here .

+1
source share

JavaScript date objects are deceptively lightweight, I worked with them in a project, and they had an insightful learning curve that took a lot of time (unlike the rest of JavaScript, which is a relative child game). I recommend allowing VB, or really something else to handle it.

But if you want to do this in javascript, without Regex (as indicated in your question), you can perform string operations on it like this:

 try { var user_input = $("#theDate").val(); var split = user_input.split(" "); // 0: date, 1: time var split_time = split[1].split(":"); // 0: hours, 1: minutes, 2: seconds d.setHours(split_time[0]); d.setMinutes(split_time[1]); } catch { // not in a valid format } 

This solution assumes that the input is in the correct format, and if an error occurs, it is not. This is not the best way to do something, but JS Date objects are seriously terrible.

+1
source share

All Articles