I'd like to check the date if it's next month from the current.
Some test cases here
2020.1.1 2019.12.30 // true
2019.11.30 2019.10.10 // true
2019.12.11 2019.12.1 // false
So as you can see, I'd like to check if the date is next month from now.
Hope to get the brilliant idea!
Best
Kinji
You could try this approach, we have to handle the case when the dates are in the same year and also for December and January of the next year.
A simple algorithm can be created, whereby we multiply the year by 12, add the month and get the difference of this score between the two dates. As long as the value of this is 1 or -1 we have months that are adjacent. I'm presuming you only need to check if the first parameter is the next month to the second parameter, so we check for a difference of 1.
function isNextMonth(timeStamp1, timeStamp2, format = "YYYY.MM.DD") {
let dt1 = moment(timeStamp1, format);
let dt2 = moment(timeStamp2, format);
return ((dt1.year()*12 + dt1.month() - dt2.year()*12 - dt2.month()) === 1);
}
let inputs = [['2020.1.1','2019.12.30'],['2019.11.30', '2019.10.10'], ['2019.12.11','2019.12.1'], ['2020.12.1','2021.1.1'], ['2020.6.1','2020.5.1'], ['2021.1.1','2019.12.1'], ['2019.3.1', '2019.4.1']];
for(let [inputa, inputb] of inputs) {
console.log(`isNextMonth(${inputa}, ${inputb}): ${isNextMonth(inputa, inputb)}`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
A very simple solution would be to use Moment’s isSame. This only checks the month. If you also want to make sure that the year matches you would have to make sure that nextMonth.getYear() matches dateToCheck.getYear()
var dateToCheck = new Date(2019, 11, 30)
var nextMonth = new Date()
nextMonth.setMonth(dateToCheck.getMonth() + 1)
moment(dateToCheck).isSame(nextMonth, 'month');
Related
So, I need to calculate age by subtracting "todays" date from the converted date of an input field, entered by the user. Although it needs cleaned up, the below code works, I had to get creative as RN uses a different JS execution environment... see here.
My question, without adding the "+1" to this snippet "b.getMonth() + 1", the math on the date subtraction comes back 1 month off every time. When I add the "+1" it works like a charm, why? If it's a logical fix, I don't mind keeping the "+1," but I would surely like to know why the "+1" is necessary.
Also, totally open to improved solutions to this problem, keep in mind I had a much simpler function that worked great while debugger was open, once closed, it did not work, see the link above.
getVerifyBirthday(birthday) {
const b = new Date();
var verify = birthday.length;
const utc2 = Date.UTC(b.getFullYear(), b.getMonth() + 1, b.getDate());
if (verify === 10) {
const splitBirth = birthday.split('-');
var mydate = new Date(splitBirth[2], splitBirth[0], splitBirth[1]);
const a = mydate;
const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const diffTime = Math.abs(utc2 - utc1);
const diffYears = (diffTime / (3.15576e+10));
this.setState({ diffYears: diffYears});
return diffYears >= 13;
} else {}
}
Update
I ended up refactoring my original function, leaving the (+1) on months due to months starting at 0, as mentioned below. I still had to split both dates, when I didn't split both, my age came back NaN/Undefined; not sure if this goes back to the RN execution environment vs browser, but I digress.
I'd make a few of my own suggestions over here:
there's no need to hussle with UTC dates (to make sure whether the user in his timezone has already reached the age of 13, assuming along the way that he or she was born in that same timezone ;)
there's no need to split mm-dd-yyyy date string to convert into Date, it may be parsed by new Date()
counting years as 365.25 days has certain error margin depending on the exact leap years quantity that passed since the user's birth year, instead whole years may be compared together with dates
To me, it makes more sense to decompose date strings into days, months and years and make decision based on full years difference minus 1 year (if the person didn't yet celebrate his/her birthday this year):
const today = new Date().toISOString().slice(0,10), // yyyy-mm-dd
birthday = '1982-06-21',
[bYear, bMonth, bDay] = birthday.split('-'),
[tYear, tMonth, tDay] = today.split('-'),
diffYears = tYear - bYear - (bMonth > tMonth || bDay > tDay ? 1 : 0)
console.log(diffYears)
.as-console-wrapper{min-height:100%;}
Months are zero-based in JavaScript Date objects. However, if you get a formatted string, they start from 1:
const date = new Date(2020, 1, 17); // 17th of February 2020
console.log("getMonth:", date.getMonth()); //month is 1
console.log("formatted:", date.toISOString()); //month is 2
So, actually what happens is that you're shifting both dates a month forward. This sort of works:
const originDate = new Date(2020, 1, 17); // 17th of February 2020
const originString = "2020-02-17".split("-");
const dateFromDate = new Date(originDate.getFullYear(), originDate.getMonth() + 1, originDate.getDate())
const dateFromString = new Date(originString[0], originString[1], originString[2])
console.log("dateFromDate:", dateFromDate); //month is 3
console.log("dateFromString:", dateFromString); //month is 3
When you do the subtraction it evens out but you can still run into an overflow of the date for months with different number of days:
const originDate = new Date(2020, 0, 31); // 31st of January 2020
const dateFromDate = new Date(originDate.getFullYear(), originDate.getMonth() + 1, originDate.getDate())
console.log("dateFromDate:", dateFromDate); // 1st of March 2020
This still works logically for most cases, however you are bound to run into a problem at some point if you shift months forward. So, instead you should be doing the opposite and subtracting 1 when converting a 1-based number into a Date object:
const originString = "2020-02-17".split("-");
const dateFromString = new Date(originString[0], originString[1] - 1, originString[2])
console.log("dateFromString:", dateFromString); //month is 2
I want to get month name from two digit month number (ex- 09). I tried with this code. But it doesn't work. The code give current month name only. What are the correct code for it?
var formattedMonth = moment().month('09').format('MMMM');
While there's nothing wrong with Kevin's answer, it is probably more correct (in terms of efficiency) to obtain the month string without going through a moment object.
var monthNum = 9; // assuming Jan = 1
var monthName = moment.months(monthNum - 1); // "September"
var shortName = moment.monthsShort(monthNum - 1); // "Sep"
You want to pass the month when you create the Moment object:
var formattedMonth = moment('09', 'MM').format('MMMM'); // September
moment(
'09', // Desired month
'MM' // Tells MomentJs the number is a reference to month
).format('MMMM') // Formats month as name
You need to pass the month as a number, not text - so...
var formattedMonth = moment().month(9).format('MMMM');
console.log(formattedMonth)
Result:
October
For those looking to do it and changing languages (locale), this is what I did
let month = moment().month(09).locale('pt-br').format('MMMM');
Could anyone please explain the below code to me?
For example, i would like to set Today's date to today (21st of November, 2012) and the end date to the 3rd of December.
The reason for this is because i want to loop through a list of items, determine whether they are in the "past", "present" or "future" and assign a class to them accordingly.
I hope this makes sense! Any help is greatly appreciated and much welcomed!
function daysTilDate(expiredate){
expiredate ="12/"+expiredate+"/2012";
var thisDay=new Date(expiredate);
var CurrentDate = new Date();
var thisYear=CurrentDate.getFullYear();
thisDay.getFullYear(thisYear);
var DayCount=(thisDay-CurrentDate)/(1000*60*60*24);
DayCount=Math.round(DayCount);
return DayCount;
}
You can simplify the method like below if you want to calculate the days to an expire date. Please note that if you don't specify a test date, it'll take the current date as the test date.
function daysTilData(expireDate, testDate) {
if(typeof testDate === "undefined"){
testDate = new Date(); // now
}
var diff = expireDate - testDate;
// minus value meaning expired days
return Math.round(diff/(1000*60*60*24));
}
alert(daysTilData(new Date("12/31/2012")));
// result 40
alert(daysTilData(new Date("12/31/2012"), new Date("1/12/2013")));
// result -12
Here's a line by line explanation.
The function declaration...
function daysTilDate(expiredate){
Takes the parameter expiredate sets it equal to the same value with "12/" prepended and "/2012" appended. so if the value of expiredate was "10", the new value is now "12/10/2012"...
expiredate ="12/"+expiredate+"/2012";
Instantiates a new Date object named thisDay using the expiredate string...
var thisDay=new Date(expiredate);
Instantiates a new Date object named CurrentDate, using the default constructor which will set the value equal to today's date...
var CurrentDate = new Date();
Gets just the Year segment from CurrentDate (which was earlier set to today's date)...
var thisYear=CurrentDate.getFullYear();
Gets the Year segment from thisDay (which was earlier set to "2012")...
thisDay.getFullYear(thisYear);
Gets the difference between thisDay and CurrentDate, which is in milliseconds, and multiplies that by 1000*60*60*24 to get the difference in days...
var DayCount=(thisDay-CurrentDate)/(1000*60*60*24);
Rounds the previously calculated difference...
DayCount=Math.round(DayCount);
Returns the difference between today and the passed-in day in December 2012...
return DayCount;
}
Note that the 2 lines that get the year segments are extraneous, because those values are never used...
I am not going to review the code, but I can answer your question of "I want to loop through a list of items, determine whether they are in the past, present, or future".
First, you want to construct your target date. If it's "now", just use new Date(). If it's a specific date, use new Date(dateString).
Second, Date objects in JavaScript have various members that return the date's characteristics. You can use this to compare dates. So, let's say you have your date strings in an array:
function loopDates(targetDateString, myDates) {
var targetDate, nextDate, status, ix;
targetDate = new Date(targetDateString);
for (ix = 0; ix < myDates.length; ++ix) {
nextDate = new Date(myDates[ix]);
if (nextDate.getFullYear() < targetDate.getFullYear()) {
status = "past";
} else if (nextDate.getFullYear() > targetDate.getFullYear()) {
status = "future";
} else {
// Year matches, compare month
if (nextDate.getMonth() < targetDate.getMonth()) {
status = "past";
} else if (nextDate.getMonth() > targetDate.getMonth()) {
status = "future";
} else {
// Month matches, compare day of month
if (nextDate.getDate() < targetDate.getDate()) {
status = "past";
} else if (nextDate.getDate() > targetDate.getDate()) {
status = "future";
} else {
// Day matches, present
status = "present";
}
}
}
console.log("Date " + myDates[ix] + " is " + status + " from " + targetDateString);
}
}
loopDates("11/17/2012", ["11/16/2012", "11/17/2012", "11/18/2012"]);
This will log:
Date 11/16/2012 is past from 11/17/2012
Date 11/17/2012 is present from 11/17/2012
Date 11/18/2012 is future from 11/17/2012
Working jsFiddle here.
If you want to work with a comprehensive Date class, use DateJS, an open source JavaScript date and time processing library with some impressive features.
I need to know the date for last Sunday for given date in php & javascript
Let's have a function give_me_last_Sunday
give_me_last_Sunday('20110517') is 20110515
give_me_last_Sunday('20110604') is 20110529
The full backup is done on Sundays = weekly. If I want to restore daily backup I need full (weekly) and daily backup. I need to copy backup files before restoring to temp directory so I restoring daily backup I need to know what weekly backup file I need to copy along the daily file.
My thought was to get Julian representation (or something similar) for the given date and then subtract 1 and check if it is Sunday ... Not sure if this is the best idea and how to convert given date into something I can subtract.
Based on Thomas' effort, and provided the input string is exactly the format you specified, then:
function lastSunday(d) {
var d = d.replace(/(^\d{4})(\d{2})(\d{2}$)/,'$1/$2/$3');
d = new Date(d);
d.setDate(d.getDate() - d.getDay());
return d;
}
Edit
If I were to write that now, I'd not depend on the Date object parsing the string but do it myself:
function lastSunday(s) {
var d = new Date(s.substring(0,4), s.substring(4,6) - 1, s.substring(6));
d.setDate(d.getDate() - d.getDay());
return d;
}
While the format yyyy/mm/dd is parsed correctly by all browsers I've tested, I think it's more robust to stick to basic methods. Particularly when they are likely more efficient.
Ok so this is for JavaScript only. You have an input that you need to extract the month, date, and year from. The following is just partly an answer then on how to get the date:
<script type="text/javascript">
var myDate=new Date();
myDate.setFullYear(2011,4,16)
var a = myDate.getDate();
var t = myDate.getDay();
var r = a - t;
document.write("The date last Sunday was " + r);
</script>
So the setFullYear function sets the myDate to the date specified where the first four digits is the year, the next are is the month (0= Jan, 1= Feb.,...). The last one is the actually date. Then the above code gives you the date of the Sunday before that. I am guessing that you can add more code to get the month (use getMonth() method). Here are a few links that might be helpful
http://www.w3schools.com/js/js_obj_date.asp
http://www.w3schools.com/jsref/jsref_setFullYear.asp
http://www.w3schools.com/jsref/jsref_getMonth.asp
(You can probably find the other functions that you need)
I hope this helps a bit even though it is not a complete answer.
Yup and strtotime has been ported to JS for eg http://phpjs.org/functions/strtotime:554 here.
final code (big thanks to #Thomas & #Rob)
function lastSunday(d) {
var d = d.replace(/(^\d{4})(\d{2})(\d{2}$)/,'$1/$2/$3');
d = new Date(d);
d.setDate(d.getDate() - d.getDay());
year = d.getFullYear()+'';
month = d.getMonth()+1+'';
day = d.getDate()+'';
if ( month.length == 1 ) month = "0" + month; // Add leading zeros to month and date if required
if ( day.length == 1 ) day = "0" + day;
return year+month+day;
}
I would like to have an input field with a button next to it.
On the input field I will enter a date like this:
2011-07-08
And when I hit the button it should read the time that has been entered on the input field and subtract it with 3 months and one day.
Is this possible?
Thanks in advance
Yes. First you read the date and you convert to a date object
var dateString = document.getElementById('id of your field').value,
date = new Date(dateString);
then you subtract 91 days and output the result
date.setDate(date.getDate() - 91);
alert(date.toString());
Here I assume for simplicity that you actually want 91 days and not 3 months and one day. If you want three months and one day you will do
date.setMonth(date.getMonth() - 3);
date.setDate(date.getDate() - 1);
alert(date.toString());
The Date object will take care of overflows, leap years and everything.
If you want to write it to same field, taking care of zeroes, you can do
function assureTwoDigits(number) {
if (number > 9) {
return '-' + number;
}
else {
return '-0' + number;
}
}
and change the last line to
document.getElementById('id of your field').value = date.getFullYear() + assureToDigits(date.getMonth()) + assureTwoDigits(date.getDate());
You can use Date objects (see here):
extract year, moth and day from the string (using a regular expression or splitting by '-')
buid a new Date object with that data
subtract the date interval
build the string back
The simplest way would be to split it into an array, then use a couple of if/else statements:
var date = (whatever you're pulling the date in as).split('-');
if (date[1] > 3)
date[1] = date[1] - 3;
else
date[0] = date[0] - 1;
var dateOverflow = date[1]-3;
date[1] = 12 - dateOverflow;
And then the same for the days.
Yes, it's possible and it's the most clean if you can do it without some arcane regex magic. Start by converting the date to a Date object:
// this will get you a date object from the string:
var myDate = new Date("2011-07-08");
// subtract 3 months and 1 day
myDate.setMonth(myDate.getMonth()-3);
myDate.setDay(myDate.getMonth(), myDate.getDay()-1);
// And now you have the day and it will be correct according to the number of days in a month etc
alert(myDate);