I need help converting this date format.
Here are the date string I receive from a server, it can be M/DD/YYYY or M/D/YYYY or MM/D/YYYY or MM/DD/YYYY.
EDIT: Sorry, my bad. After the format above, there is additional string of time HH:MM:SS AM so the complete string I receive will be M/D/YYYY HH:MM:SS AM
My problem now is I use String.substring(x, y) to extract the date, month, and year.
So far I only managed to determine the location of "/" but I'm still thinking how to use it in the substring method.
var separators = [];
for(var b = 0, c = String.length; b < c; b++){
if(String[b] === '/'){
separators.push(b);
}
}
I'm confused how to extract the date and month dynamically and then pad "0" in front of the single digit number, so I appreciate any helps. Thank you in advance.
var dt = "10/6/2012 12:34:56 AM".split(' ');
dt = dt[0].split('/');
// dt[0] => month
// dt[1] => day
// dt[2] => year
it works with any of the above format - M/DD/YYYY or M/D/YYYY or MM/D/YYYY or MM/DD/YYYY - (and it's easier than using substring)
then to add a pad to month and day just use slice() like so
dt[0] = ("0"+ dt[0]).slice(-2);
dt[1] = ("0"+ dt[1]).slice(-2);
and to get a padded data just re-join the array parts
dt = dt.join('/');
Example jsbin : http://jsbin.com/exodos/2/edit
var date= '1/3/2012'//your date string
,dateArray = date.split("/");
for(var k =0; k < 2; k++){
if((dateArray[k] + "").length ==1){
dateArray[k] = "0"+dateArray[k];
}
}
var newDate= dateArray.join("/");
jsfiddle
A regular expression can do the job. The following doesn't care whether it's a date as m/d/y or y/d/m/ or whatever, it just pads single digit numbers with a leading zero. It only works with integers, it will not behave well with decimal seconds.
function fixDate(d) {
var re = /\d+/g;
return d.replace(re, function(s) {
return (s < 10? '0' : '') + +s;
});
}
fixDate('2/3/2012 3:5:3 am'); // 02/03/2012 03:05:03 am
Related
I know this has been asked before but I can't get it to work due to my date format, which I can't change. Any help would be appreciated.
My date is in this format;
4/11/2017 12:30 PM.
If I inspect it in the developer tools it shows it as
4/11/2017 12:30 PM EDIT: Won't show with prepended space here
i.e. with a space in front, not sure if that's relevant.
Does anyone know if it's possible or how to compare it with today's date to see if it's in the past or future?
I've tried tinkering with the following code but can't get it to work because of the time, PM, and forward slashes.
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(d,m,y);
mydate=new Date('13/04/2017');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
If you have dates that are in the same format of something like 13/04/2017, you could split the string based on the slashes and compare the values starting from the right moving left.
By this, I mean when you have your array of three values for each date, you could first compare the year, if that's the same, move on to comparing the month, if that's the same then on to comparing the day.
But if for instance one of the year's is 2018 while the other is 2016, you would immediately know that the 2018 one comes later.
var st = "19/05/2019";
var st2 = "19/05/2019";
function provideLaterDate(date1, date2) {
var splitDateDate1 = date1.split("/").reverse();
var splitDateDate2 = date2.split("/").reverse();
var laterDate = false;
splitDateDate1.forEach(function(val, idx, arr) {
if ( laterDate === false ) {
if ( val > splitDateDate2[idx] ) {
laterDate = splitDateDate1;
} else if ( val < splitDateDate2[idx]) {
laterDate = splitDateDate2;
} else {
laterDate = "Both are the same";
}
}
});
if ( /\//.test(laterDate) ) {
return laterDate.reverse().join("/");
} else {
return laterDate;
}
}
To get rid of the "time pm" part, you could simply do something like:
// Assuming your date has a structure like this: 4/11/2017 12:30 PM.
var newDate = unformattedDate.split(" ")[0];
// This will separate your date string by spaces, and since there are no spaces until after the year in your date, the 0 index will give you the date minus the time and pm portion. Please pardon the not-consistent variable names.
The problem was with the way you were constructing date. Construct date like this var mydate = new Date(2017, 04, 03); and it works.
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(d, m, y);
var mydate = new Date(2017, 04, 03);
console.log(date);
console.log(mydate)
if (date > mydate) {
alert("greater");
}
else {
alert("smaller")
}
You can split the date. Be aware you should contruct your date as follows:
var date = new Date(y,m,d);
Means year first, then month and finally day, as you can see under https://www.w3schools.com/jsref/jsref_obj_date.asp
You can use the following code to perform what you want:
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(y,m,d);
newdate = '13/04/2017'
array = newdate.split('/');
var d1 = array[0]
var m1 = array[1]-1
var y1 = array[2]
mydate = new Date(y1,m1,d1);
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
You can always check the date created is correct by using the date.toString() function. Be aware 0=January for month as you can check under https://www.w3schools.com/jsref/jsref_getmonth.asp. That's why I added the -1 for var m1.
Problem:
It's not working because you are comparing a date with an Invalid date, it will always return false.
Explanation:
And the Invalid date comes from the line new Date('13/04/2017'), because 13 is expected to be a month number and not a day which is an invalid month, because the new Date(stringDate) will be treated as a local Date and not a UTC date by the browser, and it depends on which browser you are using.
You can see in the JavaScript Date Specification that:
parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
Demo:
So if we change new Date('13/04/2017') to new Date('04/13/2017') the code will work as expected:
var date = new Date();
var mydate = new Date('04/13/2017');
console.log(date);
console.log(mydate)
if (date > mydate) {
alert("greater");
} else {
alert("smaller")
}
if(date.getTime()>mydate.getTime()){
alert("greater");
}
else if (date.getTime()==mydate.getTime){
alert("simmilar");
else {alert("smaller");}
I was referring this link and as I do not have 50 reputation I am not allowed to comment in the answer so posting this question. I did not get the statement where you can see a month is subtracted from months. This can be simple one but could anyone please clarify on this?
var m = matches1 - 1; ?
function isValidDate(date)
{
var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
if (matches == null) return false;
var d = matches[2];
var m = matches[1] - 1;
var y = matches[3];
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d &&
composedDate.getMonth() == m &&
composedDate.getFullYear() == y;
}
var m = matches1 - 1; ?
months index starts from 0.
So while you think Jan is 1, it is actually 0 when you do date.getMonth().
Which is why when you get 1 from a date-string, you need to make it 0 before setting it to a date object.
In the spirt of the question, the validation function is way overdone. Only the month needs to be checked since if either the day or month is out of bounds, the month of the generated date will change.
Also the regular expression can be greatly simplified, consider (assuming the input is the peculiar US m/d/y format):
/* Validate a date string in US m/d/y format
** #param {string} s - string to parse
** separator can be any non–digit character (.-/ are common)
** leading zeros on values are optional
** #returns {boolean} true if string is a valid date, false otherwise
*/
function validateMDY(s) {
var b = s.split(/\D/);
var d = new Date(b[2],--b[0],b[1]);
return b[0] == d.getMonth();
}
var testData = ['2/29/2016', // Valid - leap year
'2/29/2015', // Invalid - day out of range
'13/4/2016', // Invalid - month out of range
'13/40/2016', // Invalid - month and day out of range
'02/02/2017']; // Valid
document.write(testData.map(function(a) {
return a + ': ' + validateMDY(a);
}).join('<br>'));
I have read a few articles but nothing seems to the point. I have created a form that records a reservation date (when a user wants to reserve a game) and the number of days they hope to borrow it for. I want to add this to the reservation date to get the date the game must be returned by. I have wrapped up my code so far into a function so that I can call it using an onclick method. What should this code look like to work properly? Almost forgot - to make life hard my date is written like this YYYY-MM-DD
function ReturnDate(){
var reservation_begin = document.getElementById('reservation_start').value;
var loan_period = document.getElementById('requested_days').value;
var reservation_end = document.getElementById('return_date');
var dateResult = reservation_begin + loan_period;
return_date.value = dateResult;
}
USING the Suggestions made by Linus
I made the following alterations but had trouble with the formatting of the return date. e.g Setting the reservation date to 2015-01-03 gave me the result of 2015-0-32 for the return date
function ReturnDate(){
var reservation_begin = document.getElementById('reservation_start').value;
var loan_period = document.getElementById('requested_days').value;
var resDate = new Date(reservation_begin);
alert(resDate)
var period = loan_period;
var output = document.getElementById('return_date');
resDate.setDate(resDate.getDate() + period);
alert(period)
//return_date.value = resDate.getFullYear() + "-" + (resDate.getMonth() + 1) + "-" + resDate.getDate();
return_date.value = resDate.getFullYear() + "-" + resDate.getMonth() + "-" + (resDate.getDate() +1);
}
As mentioned dates could be a bit tricky to handle with js.
But to just add days to a date this could be a solution?
JSBIN: http://jsbin.com/lebonababi/1/edit?js,output
JS:
var resDate = new Date('2015-02-01');
var period = 6;
var output = "";
resDate.setDate(resDate.getDate() + period);
output = resDate.getFullYear() + "-" + (resDate.getMonth() + 1) + "-" + resDate.getDate();
alert(output);
EDIT:
Added a new JSBin which is more consistent with the original code.
JSBin: http://jsbin.com/guguzoxuyi/1/edit?js,output
HTML:
<input id="reservationStart" type="text" value="2015-03-01" />
<br />
<input id="requestedDays" type="text" value="14" />
<br />
<a id="calculateDate" href="javascript:;">Calculate Date</a>
<br /><br /><br />
Output:
<input id="calculatedDate" type="text" />
JS:
// Click event
document.getElementById('calculateDate').addEventListener('click', returnDate);
// Click function
function returnDate(){
var reservationStart = document.getElementById('reservationStart').value,
requestedDays = parseInt(document.getElementById('requestedDays').value),
targetDate = new Date(reservationStart),
formattedDate = "";
// Calculate date
targetDate.setDate(targetDate.getDate() + requestedDays);
// Format date
formattedDate = formatDate(targetDate);
// Output date
document.getElementById('calculatedDate').value = formattedDate;
}
// Format date (XXXX-XX-XX)
function formatDate(fullDate) {
var dateYear = fullDate.getFullYear(),
dateMonth = fullDate.getMonth()+1,
dateDays = fullDate.getDate();
// Pad month and days
dateMonth = pad(dateMonth);
dateDays = pad(dateDays);
return dateYear + "-" + dateMonth + "-" + dateDays;
}
// Pad number
function pad(num) {
return (num < 10 ? '0' : '') + num;
}
As per my comment,
Split reservation_begin and use the Date constructor feeding in the
parts to create a Javascript date object. getTime will give you the
milliseconds since the Epoch. There are 86400000 milliseconds in a day, so
multiply this by loan_period. Add the two millisecond result together
and use the Date constructor with your total milliseconds to get
dateResult as a Javascript date object.
using Date.UTC but you don't have to.
function pad(num) {
return num < 10 ? '0' + num : num;
}
var reservation_begin = ('2015-02-01').split('-'),
loan_period = '5',
begin,
end;
reservation_begin[1] -= 1;
begin = new Date(Date.UTC.apply(null, reservation_begin)).getTime();
end = new Date(begin + 86400000 * loan_period);
document.body.textContent = [
end.getUTCFullYear(),
pad(end.getUTCMonth() + 1),
pad(end.getUTCDate())
].join('-');
Why split the date string into parts? This is to avoid cross browser parsing issues.
Why use milliseconds? This is the smallest value represented by Javascript Date, using this will avoid any rollover issues that may be present in browsers.
Why use UTC? You haven't specified the requirements for your script, and this is about as complex as it gets. You don't have to use it, you can just feed the parts into Date and use the non UTC get methods.
What does pad do? It formats the month values to MM and date values to DD.
Note that month is zero referenced in Javascript so months are represent by the numbers 0-11.
A bit confused with the third variable "reservation_end" but according to your question this solution might work.
var dateResult = new Date(reservation_begin);
dateResult.setDate(dateResult.getDate() + parseInt(loan_period));
alert(dateResult);
http://jsfiddle.net/uwfpbzt2/
Example using todays date:
var today = new Date();
today.setDate(today.getDate() + x);
where x is the number of days. Then just use getYear(), getMonth() and getDate() and format it how you like.
EDIT
var myDate = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Assuming your date is entered in dd/mm/yyyy format as inputDate then
dateParts = inputDate.split("/");
var myDate = new Date(dateParts[2], dateParts[1]-1, dateParts[0]);
Depending on the date format your split() delimiter and array positions may be different but this is the general idea.
Java script function
<script language="JavaScript">
function checkdate(date1){
var validformat=/^\d{2}\/\d{2}\/\d{4} \d{2}\:\d{2}\:\d{2}$/
if(!validformat.test(date1.value)){
alert("Invalid Date");
document.form.date1.value="";
}
}
The above is working well ! but I want to restrict the month and days accordingly.
my format = mm/dd/YYYY hh:mm:ss
Month should not be more than 12 and less than 1 and same , date should not be more than 31 and less than 1;
one thing more !
02/02/2013 00:00:00 is valid date but 2/2/2013 00:00:00 showing as a invalid date.
How to control these two situations ?
DateTime RegEx for the m/d/YYYY hh:mm:ss and mm/dd/YYYY hh:mm:ss
/^(0?[1-9]|1[012])\/(0?[1-9]|[12]\d|3[01])\/[12]\d{3} ([01]\d|2[0-3])\:[0-5]\d\:[0-5]\d$/
Explained demo: http://regex101.com/r/bS0gB6
You can try the following method:
var comp = value.split('/');
var d = parseInt(comp[0], 10);
var m = parseInt(comp[1], 10);
var y = parseInt(comp[2], 10);
var date = new Date(y, m - 1, d);
var validDateFormat = false;
if (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d) {
validDateFormat = true;
}
if validDateFormat is true, the date is valid.
You can take a look at this website which allows you to create regular expressions for numeric ranges.
That being said, you should use numerical operators provided by the language your are using (Javascript) for numeric operations and not regular expressions.
Alternatively, you could use a DateTime Picker created in JQuery, as shown here.
I need to check if the date is in the past. This is what I have so far. JSfiddle here.
var date = "09/12/2013";
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var todaysDate = +(('' + day).length < 2 ? '0' : '') + day + '/' + (('' + month).length < 2 ? '0' : '') + month + '/' + d.getFullYear();
if (date < todaysDate) {
alert("in the past");
} else {
alert("in the future");
}
Currently it is saying that the date was in the past, when it should be in the future. I know I need to parse the string as a date, but not sure how.
Help?
With that input format, you can't use a string comparison, because the least significant values are on the left. Note: I'm assuing that date is December 9th, 2013. If you're doing the American thing where it's September 12th, 2013, you'll have to adjust the indexes into parts below.
You could reverse the fields:
var date = "09/12/2013";
var parts = date.split('/');
date = parts[2] + "/" + parts[1] + "/" + parts[0];
...and then do your string comparison (being sure to construct the string for "today" in the same order — year/month/day).
If you're going to do that, you could go ahead and finish the job
var date = "09/12/2013";
var parts = date.split('/');
var date = new Date(parseInt(parts[2], 10), // year
parseInt(parts[1], 10) - 1, // month, starts with 0
parseInt(parts[0], 10)); // day
if (date < new Date()) {
// It's in the past, including one millisecond ago
}
...but of course, if you don't want the expression to be true for one millisecond ago, your string approach is fine.
var date = new Date("09/12/2013");
var d = new Date();
console.log(date>d); // true
var date = new Date("09/12/2011");
console.log(date>d); // false
JavaScript's native Date comparator only works on Date objects, whereas you are comparing Strings. You should parse date into a Date object, and then compare it with d.
//define parse(string) --> Date
if(parse(date) < new Date()) {
alert('past');
} else {
alert('future');
}