Is this a valid date in JavaScript? [duplicate] - javascript

This question already has answers here:
How can I convert string to datetime with format specification in JavaScript?
(15 answers)
How to parse a string into a date object at JavaScript?
(2 answers)
Closed 5 years ago.
my function returns the selected date of a calendar in this format:
var returnValue = "6.7.2017"; //day.month.year
When i try to use it for a new Date, it does not work:
var weekdays = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];
var wkdayname = new Date(returnValue); //Error: returnValue ist NaN
var dayName = weekdays[wkdayname.getDay()];
All I want is just the name of the weekday of this date.
Do you have any suggestions ?

The date format also has the day and month switched from the format that Date() recognizes. This function transforms a date string using . and day first notation to the valid format:
function transformDate (date){
var day_month_year = date.split(".")
return [day_month_year[1],day_month_year[0],day_month_year[2]].join("/")
}
var returnValue = "6.7.2017"; //This is a string
var weekdays = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];
var wkdayname = new Date(transformDate(returnValue));
var dayName = weekdays[wkdayname.getDay()];
alert(dayName)

You can validate a date string using the Date.parse() API.
But mind you, this API's validation is a bit loose as it accepts both ISO 8601 or RFC 2822 date formats. If it is a valid date then the API returns you the epoch time which can then be used for creating the Javascript Date object. Otherwise it returns NaN.
As for getting the day - you can use the .getDay() API.
Example:
if (Date.parse("aaabbcc")) {
console.log("aaabbcc is Valid");
}
else {
console.log("aaabbcc is invalid");
}
if (Date.parse("6.7.2017")) {
var date = new Date(Date.parse("6.7.2017"));
console.log("6.7.2017 is Valid");
console.log("The day of the week is => " + date.getDay());
}
else {
console.log("6.7.2017 is invalid");
}
References:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

Related

Convert Date string to Object with current timezone format [duplicate]

This question already has answers here:
How to convert dd/mm/yyyy string into JavaScript Date object? [duplicate]
(10 answers)
Closed 2 years ago.
I have this code to add a reminder to a calendar
function addCalendarEvent(eventDate, eventTitle){
let dateObj = new Date(eventDate);
let calendarId = "me#gmail.com";
let cal = CalendarApp.getCalendarById(calendarId);
let event = cal.createAllDayEvent(eventTitle, dateObj)
event.addEmailReminder(420)
}
The eventDate is passed into the function as a string in the format dd/MM/YYYY but the output from let dateObj = new Date(eventDate); is in american format. ie. 02/10/2020 comes out as Mon Feb 10 2020 00:00:00 GMT+0000 (Greenwich Mean Time). Any help correcting this would be great. Dates give me an absolute headache
In the end I decided that just working with date objects from the off would be easiest
This will give you the date object of the string in the format dd/MM/YYYY
function ddmmyyyytFormatterWithTime(date) {
var dateDiv = date.split('/');
var date = new Date();
date.setDate(dateDiv[0]);
date.setMonth(--dateDiv[1]); // -- since it starts from 0
date.setFullYear(dateDiv[2]--);
return date;
};
function ddmmyyyytFormatter(date) {
var dateDiv = date.split('/');
var date = new Date();
date.setHours(0, 0, 0, 0); // to reset time
date.setDate(dateDiv[0]);
date.setMonth(--dateDiv[1]); // -- since it starts from 0
date.setFullYear(dateDiv[2]);
return date;
};
var date = ddmmyyyytFormatter("10/02/2020");
var dateWithTime = ddmmyyyytFormatterWithTime("10/02/2020");

Javascript convert date string to object [duplicate]

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
I'm trying to convert a date in string format to a Date object in JavaScript. The date is coming from the openweathermap.org API, which gives the date string in the following format:
'2018-04-28 09:00:00' or 'yyyy-mm-dd hh:mm:ss'
I know that the JavaScript Date class can take other string formats of dates, but this one returns NaN when I try anything with it. How can I convert a date string, like the one above, and convert it easily to a JavaScript object? Thanks!
Since you are getting NaN while directly converting the string to date. You can split the string on spaces, - and : and then pass the value to date constructor and generate the date object.
const str = `2018-04-28 09:00:00`;
const [date, time] = str.split(' ');
const [year, month, day] = date.split('-');
const [hh, mm, sec] = time.split(':');
const dateObj = new Date(year, month - 1, day, hh, mm, sec);
console.log(dateObj);
As pointed out by #RobG, this could also be done using the regex.
const str = `2018-04-28 09:00:00`;
var b = str.split(/\D/);
var date = new Date(b[0],b[1]-1,b[2],b[3],b[4],b[5]);
console.log(date);
const str = `2018-04-28 09:00:00`,
date = new Date(...(str.split(/\D/).map((v,i)=>i==1?--v:v)));
console.log(date);
Just try new Date(str)
d = new Date("2018-04-20 09:00:00")
Fri Apr 20 2018 09:00:00 GMT+0800 (Hong Kong Standard Time)
d.getDate()
20
ref: https://www.ecma-international.org/ecma-262/6.0/#sec-date-time-string-format

JavaScript - Get system short date format

Is there any way to get system short date format in JavaScript?
For example whether system's short date is in American format eg. m/d/Y or in european eg. d/m/Y
Please note:
This is not question about formatting date or calculating it based on geolocation, but about getting the format from the OS/system
After a pinch of research I concluded that technically it's not possible to get regional settings -and by this, date format- but you can do several other things. Pick one of these options:a) The already mentioned -and outdated- "toLocaleString()" function:
var myDate = new Date(1950, 01, 21, 22, 23, 24, 225);
var myDateFormat = myDate.toLocaleString();
alert (myDateFormat);
ISSUES:1) You can't "myDateFormat.replace" to get the date mask as month is not stored as "01", "02", etc in the string but as text instead, based on locale (like "February" in English but it's "Φεβρουάριος" in Greek and who knows what in e.g. Klingon).2) Different behavior on different browsers3) Different behavior on different OS and browser versions...b) Use the toISOString() function instead of toLocaleString(). You won't get the locale date mask but get a date from which you can tell where's which part of the date (ie where "month" or "day" is in that string). You can also work with getUTCDate(), getUTCMonth() and getUTCDay() functions. You still can't tell what date format the client uses, but can tell which Year/Month/Day/etc you work with when you grab a date; use the code above to test the functions I mentioned here to see what you can expect.c) Read
Inconsistent behavior of toLocaleString() in different browser article and use the (IMHO great) solution described there
for my case i used a custom date that i know what number is day, what is month and what is year so it can possible with a simple replace statement.
let customDate = new Date(2222, 11, 18);
let strDate = customDate.toLocaleDateString();
let format = strDate
.replace("12", "MM")
.replace("18", "DD")
.replace("2222", "yyyy");
It is not possible. You can get culture from user browser and use some js libraries to convert to correct date format. http://code.google.com/p/datejs/
I made a function to determine the client date format. The function determine
the date format separator, and also determine the 1st, 2nd and third part of
the date format.
getDateFormat(){
// initialize date value "31st January 2019"
var my_date = new Date(2019,0,31);
console.log(my_date.toLocaleDateString());
// Initialize variables
var separator="";
var first="";
var second="";
var third="";
var date_parts = [];
// get separator : "-", "/" or " ", format based on toLocaleDateString function
if (my_date.toLocaleDateString().split("-").length==3){
separator = " - ";
date_parts = my_date.toLocaleDateString().split("-");
}
if (my_date.toLocaleDateString().split("/").length == 3) {
separator = " / ";
date_parts = my_date.toLocaleDateString().split("/");
}
if (my_date.toLocaleDateString().split(" ").length == 3) {
separator = " ";
date_parts = my_date.toLocaleDateString().split(" ");
}
// get first part
if (date_parts[0]==2019){
first ="yyyy";
} else if (date_parts[0] == 31){
first = "dd";
} else{
if (date_parts[0].length<=2){
first ="mm";
}
else{
first="mmm";
}
}
// get second part
if (date_parts[1] == 2019) {
second = "yyyy";
} else if (date_parts[1] == 31) {
second = "dd";
} else {
if (date_parts[1].length <= 2) {
second = "mm";
}
else {
second = "mmm";
}
}
// get third part
if (date_parts[2] == 2019) {
third = "yyyy";
} else if (date_parts[2] == 31) {
third = "dd";
} else {
if (date_parts[2].length <= 2) {
third = "mm";
}
else {
third = "mmm";
}
}
// assembly
var format = first + separator + second + separator + third;
console.log(format);
return format;
}
I've created a workaround to determine which format the user's browser is using.
This is in C# but the logic is the same:
Here are the steps:
First try to convert the user's browser date into American format (mm-dd-yyyy). Convert.ToDateTime is using the American date format.
If that fails it means the user is using European format (dd-mm-yyyy).
However, this will only cover the day 13 to 31 because this is not a valid month.
If the conversion is successful, do another check to determine if the converted date is between the current UTC day + 1 day (to cover UTC+14) and current UTC day - 1 day (to cover UTC-12).
https://www.timeanddate.com/time/current-number-time-zones.html
If the converted date is out of the current date range, it means the user's browser is using European format (dd-mm-yyyy) and you can convert it to American format if you want.
string localeDateString = "01/11/2020"; // e.g. input is using European format (dd-mm-yyyy)
var localeDate = new DateTime();
try
{
localeDate = Convert.ToDateTime(localeDateString);
//var checkTheFormatOfDateInput = localeDate.ToLongDateString();
var currentDateTime = DateTime.UtcNow;
//var currentDateTime = Convert.ToDateTime("11/01/2020");
//var checkTheFormatOfCurrentDate = Convert.ToDateTime("11/01/2020").ToLongDateString();
var currentDateTimePositive = currentDateTime.AddDays(1);
var currentDateTimeNegative = currentDateTime.AddDays(-1);
var outOfCurrentDateRange = !(localeDate.Ticks > currentDateTimeNegative.Ticks && localeDate.Ticks < currentDateTimePositive.Ticks);
if (outOfCurrentDateRange)
{
localeDate = DateTime.ParseExact(localeDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
}
catch
{
localeDate = DateTime.ParseExact(localeDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
//var checkTheEndResultFormat = localeDate.ToLongDateString();
Below is the clean code wrapped in a method:
private DateTime ConvertAmericanOrEuropeanDateFormatToAmericanDateFormat(string localeDateString)
{
var localeDate = new DateTime();
try
{
localeDate = Convert.ToDateTime(localeDateString);
var currentDateTime = DateTime.UtcNow;
var currentDateTimePositive = currentDateTime.AddDays(1);
var currentDateTimeNegative = currentDateTime.AddDays(-1);
var outOfCurrentDateRange = !(localeDate.Ticks > currentDateTimeNegative.Ticks && localeDate.Ticks < currentDateTimePositive.Ticks);
if (outOfCurrentDateRange)
{
localeDate = DateTime.ParseExact(localeDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
}
catch
{
localeDate = DateTime.ParseExact(localeDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
return localeDate;
}
A very good but lengthy answer can here found here: https://stackoverflow.com/a/9893752/2484903
A shorter one here:
let customDate = new Date(2222, 3, 8);
let strDate = customDate.toLocaleDateString();
let format = strDate
.replace("04", "MM")
.replace("4", "M")
.replace("08", "dd")
.replace("8", "d")
.replace("2222", "yyyy")
.replace("22", "yy");
console.log(format);
We create a date object of a known date and then parse the outcome.
First we look for "04" (which corresponds to 3 from the date definition); that would be the two digit month format MM. If not found, it must be the single digit format M. Afterwards do the same for day and year.
It should do the job...
function getSystemDateLocale(){
let testDate = (new Date('2000-1-30')).toLocaleDateString()
if (testDate.substring(0,2) == '30') return 'EU'
else return 'US'
}
Use Date.CultureInfo.formatPatterns.shortDate

String date to javascript date: Parse date [duplicate]

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Closed 3 years ago.
I want to parse dates (string date format to javascript date format), but I have various string date format like YYYY-MM-DD, DD-MM-YYYY and 'DD/MM/YYYY' and so..
Is there any generic procedure or way to convent from these string date format to javascript date format?
These are two libraries that I use for that:
moment.js
datejs
Here userFormat string could be in these format 'DD-MM-YYYY', 'YYYY-MM-DD', 'DD/MM/YYYY' etc..
function parseDate(dateString, userFormat) {
var delimiter, theFormat, theDate, month, date, year;
// Set default format if userFormat is not provided
userFormat = userFormat || 'yyyy-mm-dd';
// Find custom delimiter by excluding
// month, day and year characters
delimiter = /[^dmy]/.exec(userFormat)[0];
// Create an array with month, day and year
// so we know the format order by index
theFormat = userFormat.split(delimiter);
//Create an array of dateString.
theDate = dateString.split(delimiter);
for (var i = 0, len = theDate.length; i < len; i++){
//assigning values for date, month and year based on theFormat array.
if (/d/.test(theFormat[i])){
date = theDate[i];
}
else if (/m/.test(theFormat[i])){
month = parseInt(theDate[i], 10) - 1;
}
else if (/y/.test(theFormat[i])){
year = theDate[i];
}
}
return (new Date(year, month, date));
}
Just go get datejs.
http://www.datejs.com/
...and never bother with writing your own Javascript date functions again.
function dateParsing(toDate, dateFormat) {
var dt = Date.parseInvariant(todate, dateFormat); // pass date and your desired format e.g yyyy/M/dd
alert(dt); // to check date
}

Javascript Date validation for mm/dd/yyyy format in asp.net [duplicate]

This question already has answers here:
Regex to validate date formats dd/mm/YYYY, dd-mm-YYYY, dd.mm.YYYY, dd mmm YYYY, dd-mmm-YYYY, dd/mmm/YYYY, dd.mmm.YYYY with Leap Year Support
(27 answers)
Closed 6 years ago.
I want to validate BirthDate, which should be in "mm/dd/yyyy" format, on the client side.
I have tried it as following, but it is not working properly:
$("#btnUpdateEditCB3").click(function(event) {
var txtBirthDate = $('#<%= txtBirthDateCB3.ClientID %>').val();
var txtNickName = $('#<%= txtNickNameCB3.ClientID %>').val();
if (txtBirthDate != "") {
if (txtBirthDate.match(/^(?:(0[1-9]1[012])[\/.](0[1-9][12][0-9]3[01])[\/.](1920)[0-9]{2})$/)) {
alert("Please enter date in mm/dd/yyyy format");
$('#<%= txtBirthDateCB3.ClientID %>').focus();
return false;
}
}
});
Below links explains the same...see if it helps you.
Validate date using jquery
Validate date format using jquery
I recommend that you use the JavaScript Date() object along with regular expressions to validate a date. You can use a variant of this code as follows:
function ValidateCustomDate(d) {
var match = /^(\d{2})\/(\d{2})\/(\d{4})$/.exec(d);
if (!match) {
// pattern matching failed hence the date is syntactically incorrect
return false;
}
var month = parseInt(match[1], 10) - 1; // months are 0-11, not 1-12
var day = parseInt(match[2], 10);
var year = parseInt(match[3], 10);
var date = new Date(year, month, day);
// now, Date() will happily accept invalid values and convert them to valid ones
// therefore you should compare input month/day/year with generated month/day/year
return date.getDate() == day && date.getMonth() == month && date.getFullYear() == year;
}
console.log(ValidateCustomDate("1/01/2011")); // false
console.log(ValidateCustomDate("01/1/2011")); // false
console.log(ValidateCustomDate("01/01/2011")); // true
console.log(ValidateCustomDate("02/29/2011")); // false
console.log(ValidateCustomDate("02/29/2012")); // true
console.log(ValidateCustomDate("03/31/2011")); // true
console.log(ValidateCustomDate("04/31/2011")); // false
Is there any specific reason for not using datepicker formatting? Suggest using a jquery datepicker where you can set the formats.
jquery date picker date time formatting
If you want to validate date in mm/dd/yyyy format using javascript you can use the following snippet of code.
txtdate is having textbox id
Consider the below code.
function isValidDate(txtdate) {
var txtDate = "#" + txtdate;
var dateString = $(txtDate).val();
var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
if (!(date_regex.test(dateString))) {
alert("Date Must Be in mm/dd/yyyy format");
}}

Categories

Resources