I just want to ask if you have an idea on how to get the collection of date.
Sample:
Sunday = ['12/03/2017','12/10/2017','12/17/2017','12/24/2017','12/31/2017'....];
It collected all the date that will fall on Sunday.
Is there a function in javascript or php that could help me or should I do it manually?
Thanks for the suggestion
For JAVASCRIPT Use Moment.js
Your question is related to this post
Check if the input day is Monday with moment.js
moment(date).weekday(1)
For PHP Use function date($format, $timestamp) then use format l (lowercase 'L') A full textual representation of the day of the week
if(date('l', $date) == 'Sunday'){};
See full documentation here
In php
I think first select minimum & maximum date from which you want to start your collection.
E.g:
$s = '2017-01-01';
$e='2017-10-01';
Convert this to time
$stime = strtotime($s);
$etime=strtotime($e);
Get first sunday
$sunday = strtotime('next sunday', $stime);
$format = 'Y-m-d';
Initialise array with first Sunday.
$sun=array(date($format, $sunday));
Use while loop to check and make an array of Sunday's dates
while($sunday<$etime){
$sunday=strtotime('next sunday', $sunday);
array_push($sun, date($format, $sunday));
}
Print_r($sun);
Hope it'll help you out.
Another option with php is to use 2 datetimes and loop though all the sundays between them. You can use modify to set your range and format to specify the format of the date.
For example:
$dayStart = new DateTime('12/03/2017');
$dayEnd = new DateTime();
$dayEnd->modify("+1 month");
$sundays = [];
for ($dayCurrent = $dayStart; $dayCurrent <=$dayEnd; $dayCurrent->modify('next sunday')) {
array_push($sundays, $dayCurrent->format('m/d/Y'));
}
Demo
Related
I have access to financial end date and need to compute the finanacial start date based on that.
This is the logic I have currently.
moment('2017-03-31', 'YYYY-MM-DD').quarter() would give me the quarter which in this case is 1.
I then subtract 3 months using
moment('2017-03-31', 'YYYY-MM-DD').subtract(3, 'months').format('YYYY-MM-DD') which results in 2016-12-31 and then I do all kinds of hacky computations to arrive at 2017-01-01.
Is there an elegant way to compute the start date using moment API's.
So essentially, given
2017-03-31 -> output: 2017-01-01
2017-12-31 -> output: 2017-10-01
let date = '2017-12-31'
moment(date).startOf('quarter').format('YYYY-MM-DD');
If it your goal to subtract 3 months from the end date and then result in a start date (which is the first of the month) maybe use:
moment().startOf('month');
Moment Docs
var d = moment('2017-03-31', 'YYYY-MM-DD').subtract(2, 'months').startOf('month').format('YYYY-MM-DD');
http://jsfiddle.net/rLjQx/57925/
you can use as per below :
var date = moment('2017-03-31').subtract(2, 'month').startOf('month').format('YYYY-MM-DD');
enter code here
I have 2 date:
start date
<input type="text" name="startdate" value="2016-04-08">
End date
<input type="text" name="enddate" value="2016-09-02">
but how to use javascript to validate days of the end date to not less than the days from start date.
like
startdate '08' = end date '02' and 'not ok'
or
startdate '08' = end date '08' and 'ok'
thankyou
If you only have to compare the days, all you have to do is checking if one value is equal to, or higher than the other.
You can accomplish this by getting both values, take the last part, and compare those. For example:
var date = '2016-04-08';
var day = date.split('-')[2];
split turns the string into an array: MDN
The last value is the day. If you want to compare it as a number, make sure to turn it into a number (or int): MDN
DEMO
If you want to compare the whole date, which makes more sense IMO, it's a bit more tricky. In that case you have to turn the values into proper JS Date objects. Once they are both Date objects, you can compare them.
For this you can also use the split part as above. Provide the three parts (year, month, day) to the Date object to create a valid date object.
DEMO
you can do like these,
function CheckSchedulingDates() {
var SD = document.getElementById('startdate').value;
var ED = document.getElementById('enddate').value;
if (Date.parse(SD) >= Date.parse(ED)) {
return 'The ending date must occur after the starting date.'
}
}
what is the code for finding the difference between two date type inputs when clicking a service button in javascript ?
(if admission date and retire date is given and when we click service button the service period should come as alert)
For comparing dates easily i suggest you take a look at using Moment.js
More specifically moment().diff()
From the docs here's how you would compare 2 dates and get the difference in days, i'm assuming you are using jQuery.
$('.service-button').click(function(){
var subDate = $('.submission-date').val();
var retireDate = $('.retirement-date').val();
parseDateDifference(subDate, retireDate);
});
function parseDateDifference(start, end) {
start = moment(start, 'YYYY-MM-DDD');
end = moment(end, 'YYYY-MM-DDD');
var difference = start.diff(end, 'days'); // this now contains you the difference in days between the dates
alert(difference);
}
I don't really know too much about core JavaScript, just a dot of jQuery. But I know jQuery is not necessary for what I need here:
I want to use the getdate function to find out the server's day of the week. Then add a bunch of clauses like:
if its Monday add 6 to the date and return the date in MM/DD/YYYY form.
if its Tuesday add 5 to the date and return the date in MM/DD/YYYY form.
if its Wednesday add 4 to the date and return the date in MM/DD/YYYY form.
and so on until Sunday when it will add 0.
So lets say todays Monday, it will return 1/8/2012
And in real dates today's Sunday so it will really return 1/1/2012
Then I just want to call a document.write function to write the MM/DD/YYYY it returns into my HTML document.
Can anybody help me? I can clarify if you need me to...
getDay() returns the day of the week, Sunday = 0, Monday = 1, etc, etc.
So say today was Monday getDay() would return 1, which means daysToAdd would be 5.
Once we know how many days we want to add we can create a new date and add those days. We do this by getting today in milliseconds and then adding the number of days (daysToAdd) in milliseconds.
We convert days to milliseconds by multiplying by 24*60*60*1000 which is the number of milliseconds in a day.
I add 1 to the month because JavaScript returns 0 based month, but for display purposes we want to format it so that January for example is 1 not zero.
function getEndOfWeek() {
var today = new Date();
var weekDay = today.getDay();
// if you want the week to start on Monday instead of Sunday uncomment the code below
//weekDay -= 1;
//if(weekDay < 0) {
// weekDay += 7;
//}
var daysToAdd = 6 - weekDay;
var newDate = new Date(today.getTime() + daysToAdd *24*60*60*1000);
var month = newDate.getMonth() + 1;
var day = newDate.getDate();
var year = newDate.getFullYear();
var formatedDate = month + "/" + day + "/" + year;
return formatedDate;
}
You could implement in your code like so, JavaScript:
$(function() {
$("#TheDate").html(getEndOfWeek());
});
Your HTML would be something like this:
The week ends on <span id="TheDate"></span>.
You can find the jsFiddle here: jsFiddle
If you want to adjust the weekday so that you consider Monday the start of the week instead of Sunday you can do the following after you get the weekDay:
weekDay -= 1;
if(weekDay < 0) {
weekDay += 7;
}
var day = 1000*60*60*24
, nextSunday = new Date(+new Date() + day*(7-((0|(+new Date()/day)%7-3)||7)));
alert(
(101+nextSunday.getMonth()).toString().substr(1) + '/' +
(100+nextSunday.getDate()).toString().substr(1) + '/' +
nextSunday.getFullYear()
)
As fas as adding dates in JavaScipt my "DateExtensions" library does this well enough, I think. You can get it here:
http://depressedpress.com/javascript-extensions/dp_dateextensions/
Once refenced you can call "add()" as a method for any valid date and pass it any of many date parts (second, minutes, days, hours, etc). So assuming "curDate" is a valid JavaScript date object you can add 5 days like this:
newDate = curDate.add(5, "days");
Using a negative value will subtract:
newDate = curDate.add(-5, "days");
Once you get the date you want you can the use the library's dateFormat() method to display it like so:
curDate.dateFormat("MM/DD/YYYY");
There's full documentation at the link.
Integer Values for Day of Week
As for getting the integer value you want, it's actually easier that it looks (and you don't need an "if" just some math). The getDay() method of date returns the day of week with Sunday as "0" and Saturday as "6". So the week, from Sunday, would normally be:
0,1,2,3,4,5,6
First, you want to reverse that scale. That's easily done via subtraction by taking 7 (to total number of members of the set) from the value. This gives you this scale:
-7,-6,-5,-4,-3,-2,-1
We're getting closer. You want the first value to be zero as well. The simplest way (I think) to do this is to get the modulus (remainder) of the value by the total number of members. All this basically does is make "-7" a zero and leave the rest alone giving us this:
0,-6,-5,-4,-3,-2,-1
Almost done. Finally you don't want negative numbers so you need to use the Math.abs() method to eliminate the sign (get the absolute value) leaving us with our desired result:
0,6,5,4,3,2,1
For all the talk the acutual code is pretty compact:
Math.abs((cnt-7)%7)
Wrapping this into the original example gives us:
newDate = curDate.add(Math.abs((curDate.getDay()-7)%7), "days");
Server Vs Client
However take nnnnnn's comment to heart: in JavaScript the getDate() function gets the current date/time of the machine that it's running on - in the case of a web page that's the client, not the server.
If you actually meant the client time them you're set and done. If you really need the server time however that's annoying-to-impossible. If you own the server then it's actually not to hard to set up a rule that includes the current server in a cookie withing each fufilled request (you could then use my cookie library, also at the site above, to access the information!)
It's messier but depending on the server you might also be able to create an old-school server-side include that adds a bit of JavaScript to each page (preferably as a marked replace in the header) that hard-codes the date as a global variable.
You might also create a web service that returns the current server time but the client-overhead for that is insane compared to the data being delivered.
If the server's NOT yours (and you can't get the owner to provide the above) then the only real potential option is to do a straight http call and examine the HTTP "Date" header. Again however the overhead on this is immense compared to the return but it's really the only way. Any system like this would have to be very flexible however as any particular server might not return the date header or might not return it correctly.
Even if it does work understand that you might still not be getting the "server" time - or at least not the server you want. In a tiered architecture, for example an application server might render then page and hand it to a web server to return - you'd be getting the web server time, not the app server. Any number of appliances might also rewrite the headers (for example it's common to use dedicated SSL appliances to offload all the encryption work - these often re-write the headers themselves).
Sorry to get overly technical - JavaScript is definately one area where there's unfortunately rarely a "simple question". ;^)
Good Luck!
I want to get the time difference between saved time and current time in javascript or jquery. My saved time looks like Sun Oct 24 15:55:56 GMT+05:30 2010.
The date format code in java looks like
String newDate = "2010/10/24 15:55:56";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(newDate);
How to compare it with the current time and get the difference?
Is there any inbuilt function in jquery or javascript??
Any suggestions or links would be appreciative!!!
Thanks in Advance!
Update
Date is stored as varchar in the DB. I am retriving it to a String variable and then change it to java.util.Date object. The java code looks like
String newDate = "2010/10/24 15:55:56";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(newDate);
This date object was sent to client. There i want to compare the saved date with current date and want to show the time difference like 2 secs ago, 2 hours ago, 2 days ago etc... like exactly in facebook. I have gone through some date to timestamp conversion tutorial in java script and now i can get the difference in timestamp. Now, i want to know how i shall change it to some format like "2 secs or 2 days or 24 hours"??. Or, how i shall change it back to date format???
Convert them into timestamps which are actually integers and can get subtracted from each other. The you just have to convert back the resulting timestamp to a javascript date object.
var diff = new Date();
diff.setTime( time2.getTime()-time1.getTime() );
You dont need to explicit convert, just do this:
var timediff = new Date() - savedTime;
This will return the difference in milliseconds.
jQuery doesn't add anything for working with dates. I'd recommend using Datejs in the event that the standard JavaScript Date API isn't sufficient.
Perhaps you could clarify exactly what input and output you're aiming for. What do you mean by "the difference?" There is more than one way to express the difference between to instants in time (primarily units and output string formatting).
Edit: since you said you're working with jQuery, how about using CuteTime? (Demo page)