This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
Below is my JavaScript Code to try and create a Maximum date where the user can't book past so many months into the future:
var x= 12;
var arriveDate = "28/11/2018"
var currentDate = new Date();
var a_date = new Date(arriveDate);
var max_month = currentDate.setMonth(currentDate.getMonth()+ x);
if (arriveDate === ""){
$("#arrive_date_error").html("Please don't leave this field blank");
}
else if (a_date < currentDate){
console.log("Please don't select a date in the past")
}
else if (a_date > max_month){
console.log("date in future")
}
The last else if never seems to work no matter what month/day/year I try. I decided to use console.log(max_month) to see what month it was creating and it returned:
1574953488195
Rather than the correct format:
Thu Nov 28 2019 15:04:48 GMT+0000
What am I doing wrong and why is it changing the format when I try to change the month of the date object?
setMonth mutates the currentDate, it does not return a new date. You probably want to clone the date and set the months of that cloned one:
var max_month = new Date(+currentDate);
max_month.setMonth(max_month.getMonth() + x);
Related
This question already has answers here:
Convert dd-mm-yyyy string to date
(15 answers)
Closed 3 years ago.
I have a date in format dd/mm/yyyy and when I try to use getMonth() I get the dd field.
For example if I have "01/12/2019" it will take 01 as month instead of 12. Is there a way to get the month from this format?
This is my code:
var beginDate = document.getElementById("beginDate").value;
var month = new Date(beginDate).getMonth();
inside beginDate there's "01/10/2019" (October 1st 2019)
It's better to use any external libraries like momentjs or datejs. Try this it may solve your problem now.
const date = "01/12/2019";
const split = date.split('/');
console.log('day', split[0])
console.log('month', split[1])
console.log('year', split[2])
var date = moment('01/12/2019', 'DD/MM/YYYY');
console.log(date.month()+1);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
You can use something like Moment.js
const beginDate = "22/05/2019"
const date = moment(beginDate, 'DD/MM/YYYY');
const month = date.format('M');
console.log(month)
//05
Make it easy.
You don't need external libraries:
var beginDate = "01/10/2019";
var timeZone = 'your time zone'; //en-GB etc...
var month = new Date(beginDate).toLocaleString(timeZone , {month: "2-digit"}); //month = 10
I don't think that you need some external library to do this task. You should use javascript date object to get it done easily, getMonth() returns month indexed from 0 to 11. Prefer javascript always instead of unnecessarily importing external js files for libraries
var beginDate = document.getElementById("beginDate").value;
let reg = /(\d\d)\/(\d\d)\/(\d+)/gi;
const[date,mon,year] = reg.exec(beginDate).splice(1);
month = new Date(year,mon-1,date).getMonth(); // months are indexed from 0 to 11 for jan to dec
console.log(month); // 0 for jan and 11 for dec
Month in javascript is 0 indexed that mean 0 represent January, So you need to add 1 to get the month correctly
function getMonth(dt) {
let splitDt = dt.split('/');
return new Date(`${splitDt[2]}-${splitDt[1]}-${splitDt[0]}`).getMonth() + 1;
}
console.log(getMonth("01/10/2019"))
1st oct
You can get months using getMonth() as shown below, But here 0=January, 1=February etc.
var date = "05/12/2019"
var d = new Date(date);
var n = d.getMonth();
console.log(n)
This question already has answers here:
What is the best way to determine if a date is today in JavaScript?
(5 answers)
Closed 7 years ago.
I have some date in milliseconds as 1425133515000 . Now in javascript I need to verify whether 1425133515000 is today or not. Is it possible?
I need one method which takes date in milli seconds and return true if date in milliseconds is today.
New date object from miliseconds:
var dateFromMs = new Date(1425133515000);
And comparsion based on How to know date is today?:
var today = new Date();
if (today.toDateString() === dateFromMs.toDateString()) {
alert('today');
}
You could use the Date constructor taking an Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch) - which is what your integer value represents:
vat date = new Date(1425133515000);
var now = new Date();
Now all that's left is compare is whether the 2 dates represent the same calendar day:
var isSameDay =
date.getDate() === now.getDate() &&
date.getMonth() === now.getMonth() &&
date.getFullYear() === now.getFullYear();
This question already has answers here:
Convert dd-mm-yyyy string to date
(15 answers)
Closed 9 years ago.
I want to get day from date. Suppose my date is 03-08-2013 it is in d-mm-yyyy format so I just want to get dand that is 03 from above date so I try this code but it does not work
Note
I want to do it without including any js
var date = '08-03-2013';
var d = new Date(date);
alert(d.getDate());
// 2nd way
alert(date.getDate());
it alert NaN. What is missing in this code?
here is jsfiddel Link Jsfiddle Link
UPDATE
Date parsing in JS (and many languages, for that matter) is problematic because when the input is a date string, it's fairly ambiguous what piece of data is what. For example, using your date (August 3, 2013) it could be represented as
03-08-2013 (dd-mm-yyyy)
08-03-2013 (mm-dd-yyyy)
However, given just the date string, there's no way to tell if the date is actually August 3, 2013 or March 8, 2013.
You should pass your date values independently to guarantee the date is correctly parsed:
var
str = '08-03-2013',
parts = str.split('-'),
year = parseInt(parts[2], 10),
month = parseInt(parts[1], 10) - 1, // NB: month is zero-based!
day = parseInt(parts[0], 10),
date = new Date(year, month, day);
alert(date.getDate()); // yields 3
MDN documentation for Date
You can't know the regional settings of your visitors.
If you know the format of the string is always d-mm-yyyy then just parse the value yourself:
function GetDay(rawValue) {
var parts = rawValue.split("-");
if (parts.length === 3) {
var day = parseInt(parts[0], 10);
if (!isNaN(day))
return day;
}
alert("invalid date format");
return null;
}
Live test case.
Use moment.js. It's parsing ability is much more flexible than the Date class.
var m = moment('03-08-2013','DD-MM-YYYY');
var dayOfMonth = m.date();
Use this it that which you want..
var date = '08-03-2013';
date=date.replace(/([0-9]{2})\-([0-9]{2})\-([0-9]{4})/g, '$3-$2-$1');
var d = new Date(date);
alert(d.getDate());
Thanks
I have the following scenario that I am strugling to code.
I have a valuation date that is a string that is chosen by a user from a calander popup. What I need to do is take that date and pass it into a function that works outs a second date depending on the value of that date. If the first date is more than 7 days from the first day of the month use the first day of the month else use the last day of the month. This needs to happen in client side as this date need to be displayed after they have chosen the first date.
SO far I have the below:
Function CompareDate()
{ var date1 = document.getElementById("textbox1");
var x = new date();
var year = x.getYear();
var day = x.getDay();
var thisMonthFirstDay = new Date(year, month,1)
var thisMonthLastDate = ....
var 1day = 1000*60*60*24
var date1_ms = recdate
var date2ms = thisMonthFirstDay.gettime()
if(Math.round(difference_ms/1day) > 7
{var textbox = document,getelementbyid("textbox2");
textbox.value = texbox.value + thisMonthLastDate
}
else
{
textbox.value = texbox.value + thisMonthFirstDay }
}
Any examples of how this can be done would be greatly appeciated.
Cheers
getDate() will give you the day of month (e.g. 18), so if (getDate() <= 7) { outputDate = 1; } If you're having a problem getting the last day of each month for the else statement, I generally use a 12 capacity array with hard-coded values, adding 1 to February if (year % 4 == 0).
I have managed to resolve this after a finding the parseDate() function on a fiddler site. That allowed me to convert the date from this format (31 Jan 2013) to a date and then I could just use the getDay(function) to see if the day was > 7. From there it was easy!
Thanks for above suggestions.
I am developing a system which requires that you should be at least 18 years old to register.
For doing this validation i have implemented date difference in javascript in following way, but it is not accurate, is there any javascript function or other way to do this?
var d1=new Date(1985,1,28);
var d2=new Date();
var milli=d2-d1;
var milliPerYear=1000*60*60*24*365.26;
var years_old=milli/milliPerYear;
Legally being at least 18 years old is not about the amount of time corresponding to the average duration of 18 years (years aren't always the same length). It is about the current date being after your 18th birth date. Hence, you should just add 18 to the year count on the birthdate and see if this is before or after the present date, e.g.
var birthDate = new Date(1985,1,28);
var today = new Date();
if (today >= new Date(birthDate.getFullYear() + 18, birthDate.getMonth(), birthDate.getDate())) {
// Allow access
} else {
// Deny access
}
You should do the same validation on the server side as well.
Note that this also handles people born on 29th February the correct way: in this case JavaScript will create a date object to represent the 1st March 18 years later.
I like http://momentjs.com/
<script src="moment.min.js"></script>
<script>
var dob = new moment([1985,1,28]);
var age = new.moment().diff(dob, 'years')
if (age >= 18) {
...
}
</script>