From date to date validation using javascript - javascript

I want to validate from and to date. my date format is d/m/Y H:i
Here is my code:
var startDate = new Date($('#fromdate').val());
var endDate = new Date($('#todate').val());
if (endDate.getTime() <= startDate.getTime()) {
return [false,"To Date cannot be less than From Date"];
}else{
return [true,""];
}
result showing 'Invalid Date'.
Here the date format is different. How to change the date format before passing to Date function?.

You can parse the date string on your own or you can use an external library, like dayjs or momentjs
A simple parsing function could be something like this (assuming the format is the one you mentioned in your question):
function getDateFromCustomFormat(dateString) {
const dateFormatPattern = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4}) ([0-9]{2}):([0-9]{2})$/
const parts = dateString.match(dateFormatPattern)
console.log(parts)
const validFormatString = `${parts[3]}-${parts[2]}-${parts[1]} ${parts[4]}:${parts[5]}`
new Date(validFormatString)
}

Related

Compare yyyy-mm-dd formatted date strings without the Date object possible?

If I define a date range using purely date strings in yyyy-mm-dd format, it appears comparison will work just fine without using the Date object:
const dateParts = '2021-12-15--2022-01-15'.split('--') // My date range
const startDate = dateParts.slice(0, 1) // '2021-12-15'
const endDate = dateParts.slice(1) // '2022-01-15'
const date = '2021-12-14'
// Test if date is within the range
console.log(date >= startDate && date <= endDate) // false
Using any date in the above example will test successfully if what I want is ensure that the date I'm looking for is within the range.
Why is this working? If javascript was, under the hood, evaluating the date strings as numbers, this should not be working. Is it maybe just implicitly assuming it's a date without me having to parse them using new Date(date)...?
Update: I'm not looking for solutions on how to do this using the Date object, I'd be more interested in examples where comparing dates this way would NOT work.
Your code works (Or if it looks like its working) because its just a basic string comparison and not the date comparison. To do a proper date comparison, you need to do the proper string to date conversion, and then compare them.
const dateParts = '2021-12-15--2022-01-15'.split('--') // My date range
const startDate = dateParts[0] // '2021-12-15'
const endDate = dateParts[1] // '2022-01-15'
const startDateArray = startDate.split("-").map(element => parseInt(element));
const endDateArray = endDate.split("-").map(element => parseInt(element));
const date = '2022-01-15'
const dateArray = date.split("-").map(element => parseInt(element));
// Test if date is within the range
console.log(new Date(dateArray[0], dateArray[1] - 1, dateArray[2]) >= new Date(startDateArray[0], startDateArray[1] - 1, startDateArray[2]) && new Date(dateArray[0], dateArray[1] - 1, dateArray[2]) <= new Date(endDateArray[0], endDateArray[1] - 1, endDateArray[2])) // false
This should solve your problem
const dateParts = '2021-12-15--2022-01-15'.split('--'); // My date range
const startDate = dateParts[1]; // '2021-12-15'
const endDate = dateParts[0]; // '2022-01-15'
const date = '2021-12-10'
// Test if date is within the range
alert(date < startDate && date < endDate)

Unable to convert data '19-10-2002' into date

I need to pass a date parameter in format (dd-MM-yyyy) and convert in this format (yyyy-MM-dd) to send API.
So I do this:
convert(date:string){
date //is in the format(dd-MM-yyyy)
date =formatDate(date , "yyyy-MM-dd", 'en_US');
and I obtain this error:
Unable to convert "19-10-2002" into a date
Anyone can help me?
You could just do
console.log(
"19-10-2002".split('-').reverse().join('-')
)
If you want to pass a string to "formatDate" it has to be in "ISO date-time" format (the complete format is "YYYY-MM-DDThh:mm:ss.sTZD", but you can drop any part from the end and use like "YYYY" or "YYYY-MM-DD"). so the string you are passing to it is not recognized as a valid input date.
so you can use Dave's code
Here is the custom date formatter function which accepts date, format and separator/delimiter to convert the passed date with passed format.
function dateFormatter(date, format, delimiter) {
const dateItems = date.split(delimiter)
const formatItems = format.toLowerCase().split(delimiter);
const day = formatItems.indexOf('dd');
const month = formatItems.indexOf('mm');
const year = formatItems.indexOf('yyyy');
const formattedDate = ([dateItems[day], dateItems[month], dateItems[year]]).join(delimiter)
console.log(formattedDate)
return formattedDate
}
// run example
dateFormatter('02-03-2020', 'YYYY-MM-DD', '-');
dateFormatter('02/03/2020', 'MM/DD/YYYY', '/');

How to combine date and time into a single datetime object?

In my react native app i need to combine my date and time in to single datetime object. I used react native modal date time picker npm package for get date and time.
I have a datepicker returning a date string, and a timepicker returning a time string. When i try to combine it will give me a output as Invalid date.
concatDateTime = () => {
var date = this.state.date;
var time = this.state.currentTime;
var dateTime = Moment(date + ' ' + time, 'DD/MM/YYYY HH:mm');
console.log(dateTime.format('YYYY-MM-DD HH:mm'));
}
I need dateobject in ('YYYY-MM-DDTHH:mm:s') format.
You can specify the format of your input string to let moment know how to parse it.
var date = '2019-02-16';
var time = '8:24 PM';
// tell moment how to parse the input string
var momentObj = moment(date + time, 'YYYY-MM-DDLT');
// conversion
var dateTime = momentObj.format('YYYY-MM-DDTHH:mm:s');
console.log(dateTime);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Just click on below link,
https://stackblitz.com/edit/typescript-bmgx2p?file=index.ts
I hope it will solve your problem.
Another alternative:
let mDate = moment(data.StartDateLocal).tz("Australia/Melbourne");
let mTime = moment(data.StartTimeLocal).tz("Australia/Melbourne");
let x1 = {
'hour': mTime.get('hour'),
'minute': mTime.get('minute'),
'second': mTime.get('second')
}
mDate.set(x1);
this._json.header.transactionStartDateTime = mDate.format("YYYY-MM-DDTHH:mm:ss");

Convert date format 27.05.2015 01:46:32.UTC to Locale time

Can anyone help me to convert date format 27.05.2015 01:46:32.UTC to Locale time.
I tried the following code
var date = new Date('27.05.2015 01:46:32.UTC ');
date.toString();
This is also not working.
Even momentjs is also gives error to convert this format of date.
As per statement even momentjs is also gives error to convert this format of date, I have taken liberty and used momentjs here.
You need to use string-format moment constructor to pass string and format in which input string is.
Use
var t = "27.05.2015 01:46:32.UTC";
//pass dateTime string and its format, it will return
//moment object
var cdt = moment.utc(t, 'DD.MM.YYYY HH:mm:ss');
//Get date object
var date = cdt.toDate();
//Use date variable as per requiremnt
alert(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.js"></script>
The format you are using for Date is DD.MM.YYYY. So you have to change this to MM.DD.YYYY for a valid java script object.
var date = '27.05.2015 01:46:32.UTC';
var date1 = date.split(' ');
console.log(date1)
var date2 = date1[0].split('.');
console.log(date2)
var date3 = date2[1]+ '.' +date2[0] +'.'+ date2[2];
console.log(date3)
var final_date = date3 + ' ' + date1[1];
console.log(final_date);
final_date.toString();

How to automatic populate age field after filling up birthdate with a format of YYYY-MM-DD using JS

Please help. I tried this code but I wasn't able to change it's format. I need the date to accept the format YYYY/MM/DD
<script type="text/javascript">
function ageCount() {
var date1 = new Date();
var dob = document.getElementById("dob").value;
var date2 = new Date(dob);
var pattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
//Regex to validate date format (dd/mm/yyyy)
if (pattern.test(dob)) {
var y1 = date1.getFullYear();
//getting current year
var y2 = date2.getFullYear();
//getting dob year
var age = y1 - y2;
//calculating age
document.getElementById("ageId").value = age;
doucment.getElementById("ageId").focus();
return true;
} else {
alert("Invalid date format. Please Input in (dd/mm/yyyy) format!");
return false;
}
}
</script>
You just need to change the regex from
var pattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
to
var pattern = /^\d{4}-\d{1,2}-\d{1,2}$/;
And it should do.
Check Here : http://jsfiddle.net/fP875/
WARNING
But remember the regex you are using is not exactly correct. You'll need a more precise regex to check date.
Your regex will accept dates like 2014-23-56 or 9999-99-99.
I'll recommend this : https://stackoverflow.com/a/18759740/3603806
if you need accurate dates and not just formatting.
http://jsfiddle.net/EywSP/856/
http://jsfiddle.net/EywSP/854/
just take this
javascript date manipulation library [closed]
I wrote a javascript date library called moment.js
https://github.com/moment/moment
It creates date wrapper objects so that it doesn't have to modify
Date.prototype.
It includes parsing from strings, date objects, and unix timestamps.
It can format based on replacement patterns ("dddd, MMMM Do YYYY,
h:mm:ss a") and also includes time ago ("2 days ago", 6 months ago")

Categories

Resources