I want to get start and enddates for upcoming 4 weeks(only weekdays).
Suppose today's date is 2015-12-01 then the result should be as below
Week0 will have StartDate = 2015-11-30 and EndDate = 2015-12-04
Week1 will have StartDate = 2015-12-07 and EndDate = 2015-12-11
Week2 will have StartDate = 2015-12-14 and EndDate = 2015-12-18
Week3 will have StartDate = 2015-12-21 and EndDate = 2015-12-25
Here date of Week0 should be calculated from current date.
Try the moment library. It's pretty easy to use, so you should be able to figure out quickly, how to do this.
var date = moment(yourdate);
// iterate by date.add(1, "week")
var start = date.clone().startOf('week');
var end = date.clone().endOf('week');
//use .format('YYYY-MM-DD'); to print out
Here is how you would use the Moment.js library (as mentioned in the comments) to achieve the output you desire. It's quite easy by using the built in functions (to see the result, hit F12 on your keyboard or open the console some other way)
var weeks = 4;
for (var i = 0 ; i < weeks ; i++) {
var start = moment().startOf('isoweek').add(i, 'weeks');
var end = start.clone().add(4, 'days');
console.log("Week%d will have StartDate = %s and EndDate = %s", i, start.format('YYYY-MM-DD'), end.format('YYYY-MM-DD'));
}
<script src="http://momentjs.com/downloads/moment.min.js"></script>
Couple simple built in functions at work here, namely:
moment, which is an instance of the moment class - essentially a datetime string.
startOf, pretty self explanatory, finds the exact datetime of when (in this case) the start of the week was
add, which adds a certain amount of x i.e. days, weeks, months etc. to the moment instance
clone, a necessary step which clones the original moment to prevent it from being modified by the end variable.
and format, pretty obvious, formats the moment based on the string given as its argument.
Take a look at the Moment.js docs and have a little decipher of the code; it will help you understand Moment.js as a library much better. Hope this helps.
Related
I'm trying to subtract days by a constant integer in MM/DD format. Here is my current code in javascript.
var d = new Date();
var n = d.getDate();
var m = d.getMonth() +1;
var q = document.getElementsByClassName('four-days-back');
for(var i =0; i<q.length; i++){
var o =4;
var z = d.setDate(d.getDate()-o);
q[i].innerHTML = m + "/" + z;
}
output is: 11/1572387207470.
As there is not yet an accepted answer to this post I put together some of the aspects mentioned in the comments and compiled them into a working fiddle. Please do not feel offended if it appears to you that I hijacked your contribution.
One point that remained unclear to me was the origin of the date. Maybe it is only one date (the current one) OP wants to subtract from? This would only require one conversion/subtraction to be done. On the other hand, maybe OP wants the subtraction to be done on a number of "input cells"? In the following example I added some HTML to the question in which I provide input dates in the column preceding the target cells with class "four-days-back".
The script loops over all the target cells and fills them with dates 4 days before the dates given in the column before that.
Since the year is not defined in the date column it needs to be defined nonetheless. The year becomes important because of leap year implications. In my example I assume that the current year applies.
[[ This answer is a "Vanilla-JS" one, using ES2015 arrow notation and the ES2017 element String.prototype.padStart(). Therefore it will not work in IE browsers. It will need to be adapted in order to work in these browsers. ]]
var y = new Date().getFullYear();
[...document.querySelectorAll('.four-days-back')].forEach(el=>{
var md=el.previousElementSibling.innerText.split('/');
var mm,dd;
var dt=new Date(y,md[0]-1,md[1]-4,12);
el.innerText=(dt.getMonth()+1+'').padStart(2,'0')
+'/'+(dt.getDate()+'').padStart(2,'0')
});
<table>
<tr><th>topic</th><th>date</th><th>4 days before</th></tr>
<tr><td>one</td><td>03/02</td><td class="four-days-back"></td></tr>
<tr><td>two</td><td>08/14</td><td class="four-days-back"></td></tr>
<tr><td>three</td><td>09/03</td><td class="four-days-back"></td></tr>
<tr><td>four</td><td>10/01</td><td class="four-days-back"></td></tr>
</table>
Maybe the line var dt=new Date(y,md[0]-1,md[1]-4,12); deserves some explanation? I set the date to given year, month, date and hour values. The year is the current year, month and date values I take from the preceding column (note that JavaScript month numbering starts at 0) and I use an hour value of 12 in order to avoid any "daylight saving issues".
Not Javascript or Jquery, but PHP can be helpful.
e.g
<?php
$one = strtotime("-4 days");
echo "<td>".date("m/d", $one)."</td>"
?>
I got the date in ISOFormats and time in 12hrs format. i need to combine togeather and get the output in ISOFormat using javascript. Im doing this in reactJs so using external libraries is fine
date = "2019-02-19T00:00:00.000Z"
startTime = "04.42PM"
outputDateTime = "2019-02-19T11:12:37.680Z"
Have a look at momentjs parse function.
Use it to convert the dates to moment objects and directly add them using the add function.
Example here
If you go pure vanilla I think this is fairly simple (AFAIK you only need hours and minutes and the zone is always fixed, if not, upgrade).
var yourDate = "2019-02-19T00:00:00.000Z";
var yourTime = "04.42PM"
var dat = yourDate.split("T")[0];
var minutes = yourTime.split(".")[1].slice(0,2);
var isPm = yourTime.split(".")[1].slice(2) === "PM";
var hours = isPm ? parseInt(yourTime.split(".")[0]) + 12 : yourTime.split(".")[0];
var date = new Date(dat+ "T" +hours+":"+minutes+":00Z");
Basically, I decomposed the input strings into interesting parts, compensated for PM if needed and put them back together :)
I am trying to have a date entry box which has the following restrictions. Date must be today's date or earlier, but not more than 1 year previous. I have the following line:
if (myFDGDT - todayDate > 0 || (myFDGDT - todayDate)/86400000 < -365)
The first portion of that creates the appropriate alert when some enters a date after today's date. Not sure about the best way to cap the entry to a year previous. Attempted a few items, but the above was just an example of my last attempt. This is also written in a dependency and not in the Global JavaScript of our entry client.
Here is a snippet that will generate a Date object that is one year ago. You can compare against it as needed using greater than/less than operators.
var oneyear = new Date('01/01/1971'); // from unix epoch
var now = new Date();
var oneyearago = new Date(now - oneyear);
alert(oneyearago);
If you are manipulating dates a lot in your app you should consider using the momentjs library. For your problem the solution would be something like:
var momentdate = moment(date);
if (momentdate.isAfter(momentdate.add(1, 'year') ||
momentdate.isBefore(momentdate.startOf('day')) {
// Invalid date?
}
Hope this helps.
I have used the "datetime-local" input to get a start date and an end date from the user to put into the native calendar. This is my code to get and format the "datetime-local":
var s = $("#startDate").val();
var startDate = moment(s).toDate();
var e = $("#endDate").val();
var endDate = moment(s).toDate();
This code takes the correct date, but it makes the time set to an all day event. For example, if I put in 1:00 o'clock on 7/21/2014 as the start date and then 1:00 o'clock on 7/22/2014 it will create an all day event on 7/21/2014.
Here is a JSFiddle
You appear to have a typo. Pass e to build the endDate, not s.
var s = $("#startDate").val();
var startDate = moment(s).toDate();
var e = $("#endDate").val();
var endDate = moment(e).toDate(); // <==== this line had used the wrong variable
Or, you could instead just call these inline to avoid confusion:
var startDate = moment($("#startDate").val()).toDate();
var endDate = moment($("#endDate").val()).toDate();
As to why this created an "all day event" - I can't be absolutely certain since I'm not familiar with the particular calendar API you're using. However, it's possible that since you were sending the same start and end time, that it interpreted that as an all day event. I believe fixing the typo will solve the issue.
The code below works fine if the 2 dates are within the same year, but seems to break if the end date is in the following year. Could anyone point me in the right direction as to why?
Both vars are date pickers in the format DD/MM/YYYY.
Thanks in advance.
$(document).ready(function() {
$("#start").change( function() {
var startDate = $('#start').val().replace('/','');
var endDate = $('#due').val().replace('/','');
if(startDate > endDate){
$("#due").val($(this).val());
}
});
});
This comparison will only work if the dates are in format YYYY-MM-DD. If val() is a string (in the format DD/MM/YYYY), you can do:
var startDate = $('#start').val().split('/').reverse().join('-');
var endDate = $('#due').val().split('/').reverse().join('-');
Then you can compare them.
if your startdate is like 10/12/2012 and your enddate is the 10/01/2013 take a look at your code and what it generates:
"10/12/2012" -> "10122012”
"10/01/2013" -> "10012013"
what you do is comparing 2 strings against each other, and at the third position the first string is bigger than the second.
you should us Date to compare dates.
if you want it easier, take a look at moment.js
Like Patrick James McDougle said, it's probably not a good idea to compare dates by strings. Try the Date object, like this:
$("#start").change( function() {
var startDate = new Date($('#start').val());
var endDate = new Date($('#due').val());
if (startDate > endDate){
$("#due").val($(this).val());
}
});
You are comparing, for example, 1232013 (1/23/2013) with 12232012 (12/23/2012). The latter is a larger numeric value, but it is an earlier date.