Need to validate dd/mm/yy hh:mmtt in Javascript - javascript

I am trying this to validate the date.However I am not too sure about what is wrong with this.
Note- I my application there is no space between mm(minuted) and AM/PM.
var date = '21/01/13 6:40AM';
var myRegex = /0?[0-31]\d\/0?[0-12]\d\/\d{2} [0-11]\d:[0-59]\d[AP][M]/;
if (myRegex.test(date)){
// Ok to proceed
}
I tried the following by breaking the date and time separately i.e the following combination
var date = '21/01/13'
var myRegex = /0?[0-31]\d\/0?[0-12]\d\/d{2}/;
However for the time part i.e 6:40AM.I am not able to validate it with
var myRegex = /[0-11]\d:[0-59]\d[AP][M]/;
Could you please help me out.

Try This One. Leap year supported. example: http://jsfiddle.net/Vk268/
^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$

Try This :
var regex = /^([0-11]\d):([0-59]\d)\s?(?:AM|PM)?$/i;
Will work for : "06:40am"

I suggest you to check actual validity not just syntax. check this post which uses datejs
Jquery DateJs, is there validation for full date?

One way to validate date and time strings is to create a date object and see if the parts match, e.g.
function validateDateString(s) {
var b = s.split(/[\/ :]/g);
var ap = s.substring(-2).toLowerCase();
var h = parseInt(b[3], 10) + (ap == 'am'? 0 : 12);
var min = parseInt(b[4],0);
var y = +b[2] + (b[2] < 50? 2000 : 1900);
var d = new Date(y, --b[1], b[0], h, min, 0, 0);
var apValid = /am|pm/.test(ap);
// Only need to test two parts of date and hours
return d.getMonth() == b[1] && d.getDate() == b[0] && d.getHours() == h && apValid;
}
console.log(validateDateString('21/01/13 6:40AM')); // true
You could use a regular expression too, and if ES5 compliant browsers are all you need to support you could reformat the string as an ISO 8601 compliant string a pass it to Date.parse. But that won't work in many browsers in use.

Related

determine if a timestamp in this format is within a particular range in JavaScript

I have a bunch of timestamps that have the following format: Year:Month:Day:Hour:Minute:Second, for example, 2017:01:01:23:59:59. All domains are zero-padded decimal numbers.
I am trying to write a function to determine if a given timestamp is within a range:
function isBetween(start, end, toCompare) {
}
for example, isBetween('2017:01:01:23:59:58', "2017:01:02:23:59:58", "2017:01:01:23:59:59") should return true as "2017:01:01:23:59:59" is between '2017:01:01:23:59:58' and "2017:01:02:23:59:58"
I couldn't find a clean way to do it. Can someone help me with this?
In JavaScript, Date objects can be compared fairly easily. However, as you've probably noticed, the format of the string you provided is not a format that can be parsed by JavaScript's Date object, so we will first have to fix that. Fortunately, this format is extremely predictable.
The first thing I notice is that the "Month" and "Date" are preceded by a zero if they're a single digit. This means that the date portion is always the exact same amount of characters (10). Because this is the case, we can use String.prototype.substring() to get the first 10 characters for the date, and get everything after the 11th character to get the time while skipping the colon in the middle.
var datetime = "2017:01:01:23:59:58";
var date = datetime.substring(0, 10);
var time = datetime.substring(11);
console.log("Date: " + date);
console.log("Time: " + time);
Now that they're separate, all we need to do is replace the colons in the date with forward slashes, then concatenate it with the time separated by a space. After this, we will have a date string in the MM/dd/yyyy hh:mm:ss format, which we can then parse using JavaScript's built in Date class.
var input = "2017:01:01:23:59:58";
var date = input.substring(0, 10).replace(/:/g, "/");
var time = input.substring(11);
var datetime = date + " " + time;
console.log(new Date(datetime));
Now we can throw this into it's own function, then use simple comparison to figure out if toCompare is between start and end.
function isBetween(start, end, toCompare) {
var startDate = convertDate(start);
var endDate = convertDate(end);
var compareDate = convertDate(toCompare);
return compareDate > startDate &&
compareDate < endDate
}
function convertDate(input){
var date = input.substring(0, 10).replace(/:/g, "/");
var time = input.substring(11);
var datetime = date + " " + time;
return new Date(datetime);
}
var between = isBetween("2017:01:01:23:59:58", "2017:01:02:23:59:58", "2017:01:01:23:59:59");
console.log(between)
This could work for you:
function isBetween(start, end, toCompare) {
start = dateGenerator(start)
end = dateGenerator(end)
toCompare = dateGenerator(toCompare)
if(start <= toCompare && toCompare <= end) return true
return false
}
function dateGenerator(str) {
str = str.split(":")
let date = new Date(`${str[0]}-${str[1]}-${str[2]}`)
date.setHours(str[3],str[4],str[5])
return date.valueOf()
}
const truthy = isBetween('2017:01:01:23:59:58', "2017:01:02:23:59:58", "2017:01:01:23:59:59")
console.log(truthy)
Firstly get individual values and add accordingly to Date constructor of JS and set the hours accordingly.
For comparison we can convert this unix figures (valueOf), hence it will be easier to compare.
This may seem as complex approach but it works.

get date and month from html5 datefield javascript

I have a date field which looks like this
var date_input = document.getElementById('date_cust');
date_input.onchange = function(){
alert("The date you selected is : "+date_input.value);
}
<input autocomplete="off" type="date" class="form-control" id="date_cust" name="date_cust" required />
and resulted/alerted something like this:
``The date you selected is: 2020-01-20``
I want to know is there any ways to get only the date and the month, because I want to compare the date and the month with the date and the month which I already set, for example, 31st of March (31-03 / 03-31). Something like this.
var 31march = '03-31';
if (extracted_data == 31march) {
alert("Happy Birthday");
} else {
alert("Not your birthday yet.")
}
I already tried to parse the value like this:
var date_input = Date.parse(document.getElementById('date_cust').innerHTML);
but it resulted in NaN
is there any other ways for this case?
Thank you in advance.
Use getMonth() from new Date():
const myDate = new Date('2020-01-30')
console.log(myDate.getMonth())
//0 = january
//1 = February
...
DOCS
You can split the date and get the parts that you need
var dateArr = date_input.value.split("-");
console.log('year: ' + dateArr[0])
console.log'month: ' + (dateArr[1])
console.log('day: ' + dateArr[2])
var new_date = dateArr[2] + '-' + dateArr[1];
console.log(new_date)
To get the date from the input element, you must use the new Date() method passing the value attribute of the input as param.
var dateCustom = new Date(this.value);
this refers to the input element because you will use in the event handler.
Then, use the getDate() and getMonth() JS methods to extract the day of the month and the month.
var date_input = document.getElementById('date_cust');
date_input.onchange = function(){
var dateCustom = new Date(this.value);
document.getElementById('day').textContent = dateCustom.getDate();
document.getElementById('month').textContent = dateCustom.getMonth() + 1;
}
<input autocomplete="off" type="date" class="form-control" id="date_cust" name="date_cust" required />
<p id="day"></p>
<p id="month"></p>
Since parsing of even the formats specified in ECMA-262 is not consistent, it is recommended to never rely on the built–in parser and to always manually parse strings, say using a library and provide the format to the parser.
E.g. in moment.js you might write:
let m = moment(date_input.value).format('MM-DD');
Where:
MM stands for month number (eg: 01-12)
DD stands for day of the month (eg: 01-31)
Read the moment docs here: https://momentjs.com/docs/
More information about why it is giving you a NaN as result can be found here: Why does Date.parse give incorrect results?
use this:
getDate()
const yourDate = new Date('2019-03-10');
console.log(yourDate.getDate())
console.log(yourDate)
**variable in js can't be start with a number "var 31march = '03-31';"
should be for example var march31 = '03-31' ;
**
these are the set of rules you should consider:
1-Names can contain letters, digits, underscores, and dollar signs.
2-Names must begin with a letter
3-Names can also begin with $ and _ (but we will not use it in this tutorial)
4-Names are case sensitive (y and Y are different variables)
Reserved words (like JavaScript keywords) cannot be used as names
Here is the code that might work for you:
var date_input = document.getElementById('date_cust');
date_input.onchange = function() {
var birthday = '3-31';
let dateSelected = new Date(date_input.value);
let dateMonth = (dateSelected.getMonth() + 1) + '-' + dateSelected.getDate() ;
if (dateMonth === birthday) {
alert("Happy Birthday");
} else {
alert("Not your birthday yet.")
}
}
but it is better to split the date input value by - so that you know first value is the year, and the second one is a month and third one is a year.
Here is my code pen link: https://codepen.io/gideonbabu/pen/ZEYdzLj

How to convert 112889 (mmddyy) to 11/28/89 or 11/28/1989

How do we convert this unformatted date of 112889 (mmddyy) to specific format like 11/28/89?
console.log(new Date('112889'))
// I got this: Sat Jan 01 112889 00:00:00 GMT+0800
I have searched anywhere in google concerning this but found none specific answers.
Reference searches:
https://forums.asp.net/t/1987249.aspx?How+can+i+convert+Date+1365715800000+format+to+MM+dd+yyyy
Convert number into date using javascript
Im also thinking about momentjs formatting but couldn't find any doc about this or did i only missed it
Using the momentjs library you can specify what format your input string will come i.e. MMDDYY in this case.
var d = new moment("112889", "MMDDYY");
document.getElementById('dated').innerText = d.format('MM/DD/YYYY');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<div id="dated"></div>
Please have a look moment.js library. try this code
var date = moment('112889',"MMDDYY").format('MM/DD/YY');
console.log(data);
If you don't want to use a library and if you know that your input is always going to be of mmddyy format, you can do something like this:
var str = '112889';
var arr = str.match(/.{1,2}/g); // Splits string into 2 character chunks
var d = new Date(arr[2],arr[0],arr[1]);
console.log(d);
But this is quite not correct since if you give a string like 112804, JS (or anyone for that matter) will not know if it is 1904 or 2004 and it'll pick up 1904. In that case, you should specify explicitly:
var str = '112896';
var arr = str.match(/.{1,2}/g); // Splits string into 2 character chunks
var d = new Date(arr[2], arr[0], arr[1]); // new Date(yy,mm,dd);
var presentYear = Number((new Date()).getFullYear());
var dateYear = Number(d.getFullYear());
if (presentYear >= dateYear + 100) { // If adding 100 to year makes it greater than present year, then move to 2000s
d = new Date('20' + arr[2], arr[0], arr[1]);
}
console.log(d);

NaN javascript error when calculating between dates with timestamp

I would like to begin by saying i looked at multiple threads in this forum before posting. Wasnt able to find my solution :(
Issue: getting a NaN error when trying to find the difference between two dates with a timestamp from two textboxes.
The date format i'm using is DDMMYYYY HH:MM - 27/01/2015 00:00
code below.
thank you in advance for this super helpful forum :)
function stringToDate(s) {
var dateParts = s.split(' ')[0].split('-');
var timeParts = s.split(' ')[1].split(':');
var d = new Date(dateParts[0], --dateParts[1], dateParts[2]);
d.setHours(timeParts[0], timeParts[1], timeParts[2]);
return d;
}
function test() {
var a = textbox_1.value;
var b = textbox_2.value;
alert(stringToDate(a) - stringToDate(b));
}
Your date has / as separator but you are splitting the string on -. Change
var dateParts = s.split(' ')[0].split('-');
to
var dateParts = s.split(' ')[0].split('/');
Also, your time part has only hours and minutes, so there is no timeParts[2] present, just remove it from the setHours() call. Like this:
d.setHours(timeParts[0], timeParts[1])
Fiddle: http://jsfiddle.net/2evj59d1/
EDIT
Your code returns the difference in milliseconds. To convert it into date format just change
alert(stringToDate(a) - stringToDate(b));
to
alert(new Date(stringToDate(a) - stringToDate(b)));
The code is trying to parse a time in the format HH:MM:SS. Skip the third part:
d.setHours(timeParts[0], timeParts[1]);
You can convert the date into milliseconds, get the difference and get the date back.
Fiddle
JSCode:
var a = new Date();
a.setDate(15);
a = a.getTime();
var b = new Date();
b.setDate(32);
b = b.getTime();
var c = b - a;
var date = new Date(c);
alert(date.getDate() - 1);
for those who may have stumbled upon my post, i found my answer at the link below by user benjour.
How do I get the difference between two Dates in JavaScript?

Javascript date of birth conundrum

I need to validate a primitive date of birth field input in the format of:
'mmmyyyy'
Where the first 3 characters of the string must be an acceptable 3-letter abbreviation of the months of the year.
It can be lowercase, or uppercase, or a mix of any so long as it spells out jan or feb or mar etc etc etc.
There is no built-in method that I am aware of that has a ready array of this specific format of a month to be able compare against user input. I was thinking that I could maybe use the localeCompare() method in a for loop to test if the output is not 0 then append an error message accordingly.
function dateTester() {
var d = new Date(),
i,
mo = [],
moIsValid;
for (i = 0; i < 12; i += 1) {
d.setMonth(i);
mo.push(d.toLocaleString().split(' ')[1].substr(0, 3));
}
return new RegExp('^(' + mo.join('|') + ')', 'i');
}
var moIsValid = dateTester();
alert(moIsValid.test('fEb1992'));
If you don't want the user's current locale name for the days to be valid, then just switch toLocaleString() to toString(). But then, why don't you just do this instead:
var moIsValid = /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i;
alert(moIsValid.test('fEb1992'));
I like this concise function for validating your input:
var months = "janfebmaraprmayjunjulaugsepoctnovdec";
function validate(dateString) {
return dateString.length == 7 &&
!(months.indexOf(dateString.substr(0,3).toLowerCase()) % 3) &&
isFinite(dateString.substr(3));
}
http://jsfiddle.net/gilly3/NR3aG/
Unless you just really, really want to check a month with a "dynamic" test, you can do:
var months = 'jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec';
months.indexOf('JaN1975'.toLowerCase().substring(0,3)
Checking with:
console.log(months.indexOf('JaN1975'.toLowerCase().substring(0,3)) != -1);
console.log(months.indexOf('oct1975'.toLowerCase().substring(0,3)) != -1);
console.log(months.indexOf('FEB1975'.toLowerCase().substring(0,3)) != -1);
console.log(months.indexOf('Ja1975'.toLowerCase().substring(0,3)) != -1);
console.log(months.indexOf('091975'.toLowerCase().substring(0,3)) != -1);
http://jsfiddle.net/ELMFu/
Gives:
true
true
true
false
false
new Date(str.replace(/(\D+)(\d+)/, "1 $1 $2"))
EDIT: use isNaN to test whether the date failed to parse.

Categories

Resources