I have created a small function that i need on my site successfully in php. But i now realise i actually need this in javascript or jquery as PHP will only excute this code on load.. i need this function to work with onchange on a select. The code below is my function.. Can anyone point out where i start to convert this into js/jquery like code:
function setTrnTime ($hr, $journeyTime){
date_default_timezone_set('GMT');
//convert current hour to time format hour
$currentHour = (date("H", mktime($hr)));
// Journey time in hours
$journey = $journeyTime
$journey = $journey/60; // Get hours
$journey = ceil($journey); // Round off to next hour i.e. 3 hours 20mins is now 4 hours
// New Hours
$NewHour = (date("H", mktime($journey)));
$Newhour = $NewHour*60*60; // convert to seconds
// Final hour is Current Hour - JourneyTime (Hours)
$trnHour = (date('H', mktime($currentHour-$NewHour)));
return $trnHour;
}
With the code above, if i pass two values 06, 60: that would mean my answer would be 05. e.g. 06 is 6am. 60 is 60mins.. so 6am - 60mins = 5am.
You can do the same in javascript using the Date object, see info here
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
EDITED: Added some code, also not even using the Date object.
But do you need something that complex, doesn't the following do what you are after with less steps.
http://jsfiddle.net/WWTDc/
If hr is a Date object, then it's very simple. Otherwise you can create a Date object and set its hour:
//! \param[in] hr Date object or hour (0--23)
//! \param[in] journeyTime journey time in minutes.
function setTrnTime(hr,journeyTime){
var end;
if(typeof(hr) === 'number'){
end = new Date();
end.setHours(hr);
}
else
end = hr;
return (new Date(end - journeyTime*60*1000)).getHours();
}
This will return the hour (demonstration).
See here for information about Date object in JavaScript.
Related
I am trying to compare two dates in javascript without the time portions. The first date comes from a jquery datepicker and the second date comes from a string.
Although I could swear that my method worked a while ago it looks like it is not working now.
My browser is Firefox but I also need my code to work in IE.
function selectedDateRetentionDaysElapsed() {
var dateSelectedDate = $.datepicker.parseDate('dd/mm/yy', $('#selectedDate').val());
// dateSelectedDate is equal to date 2015-09-30T14:00:00.000Z
var parsedRefDate = isoStringToDate('2015-11-10T00:00:00');
var reportingDate = getPredfinedDateWithoutTime(parsedRefDate);
// reportingDate is equal to date 2015-11-10T13:00:00.000Z
var businessDayCountFromCurrentReportingDate = getBusinessDayCount(dateSelectedDate,reportingDate);
// businessDayCountFromCurrentReportingDate is equal to 39.9583333333336
if (businessDayCountFromCurrentReportingDate >= 40) {
return true;
}
return false;
}
function isoStringToDate(dateStr) {
var str = dateStr.split("T");
var date = str[0].split("-");
var time = str[1].split(":");
//constructor is new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
return new Date(date[0], date[1]-1, date[2], time[0], time[1], time[2], 0);
}
function getPredfinedDateWithoutTime(myDate) {
myDate.setHours(0,0,0,0)
return myDate;
}
My issues are...
My isoStringToDate function is returning a date with a time even though I am not specifying a time.
The setHours call on a date does not seem to be working either.
Can someone please help me with this.
The simplest way to get the number of whole days between two dates is to create two date objects for the subject dates that are set to the same time. Noon is convenient as it means the date part is unaffected by daylight saving (some places introduce it at midnight) if you happen to print out just the date part.
The following does all calculations in the time zone of the host system. UTC could be used (and the hours set to 0 as daylight saving isn't an issue at all), but it's more to type.
E.g.:
function differenceInDays(d0, d1) {
// Copy dates so don't affect originals
d0 = new Date(+d0);
d1 = new Date(+d1);
// Set to noon
d0.setHours(12,0,0,0);
d1.setHours(12,0,0,0);
// Get difference in whole days, divide by milliseconds in one day
// and round to remove any daylight saving boundary effects
return Math.round((d1-d0) / 8.64e7)
}
// Difference between 2015-11-12T17:35:32.124 and 2015-12-01T07:15:54.999
document.write(differenceInDays(new Date(2015,10,12,17,35,32,124),
new Date(2015,11,01,07,15,54,999)));
I have this JS script:
if ($('.count-down').length !== 0){
$('.count-down').countdown({
timestamp : (new Date()).getTime() + 24*60*60*1000
});
}
It provides +24 hours as 24*60*60*1000 so script starts count down from 24:00:00
I need to give this script my event date as valuable format Y.m.d H:i I.E. 2014.12.31 12:00, that it would calculate the time difference between now and add it to the code.
var difference = getTimeDifferenceFromNow('2014.12.31 12:00')
timestamp : (new Date()).getTime() + difference
Substract two Date instances, you will get the length between in millisecond.
function getTimeDifferenceFromNow(timeString) {
return new Date(timeString) - new Date();
}
getTimeDifferenceFromNow('2014.12.31 12:00') // 818501769, roughly 9 days and half in the future.
How could this work? When you substract two Date instances, their valueOf() method is called internally, which will convert them to timestamp. Then you are actually subsctracting two timestamps, finally get a number of millisecond.
EDIT
However, I was wondering why you did in that way? If you want the timestamp of a given date/time, why don't you just instantiate it and grab its timestamp?
new Date('2014.12.31 12:00').getTime() // 1419998400000
This was the final solution:
var eventdate = new Date("January 1, 2015 1:00:00").getTime();
if ($('.count-down').length !== 0){
$('.count-down').countdown({
timestamp : eventdate
});
}
We have a system script that runs everyday at 1 AM PST. We have users around the world. We want to provide a simple web page that uses JavaScript to show 1 AM PST in the user's local timezone. For instance, a user in New York City should see 4 AM PST as the time the system script will run.
The PST time format is HH:MM DD.YYYY.
This only needs to work on mobile Safari.
What's the best way to do this?
The code would something like this:
alert(new Date(your_pst_server_time).toLocaleString());
You can use the .getUTCHours() and .getTimezoneOffset() methods of the new Date() object. For the ease of use, I attached this new function to that object. It will accept a parameter that specifies the time format that gets returned.
Date.prototype.getLocalTime = function (format){
var date = new Date();
var finalTime = ((date.getUTCHours()-2))-(((date.getTimezoneOffset())/60));
if (format+'' != '24'){
if (finalTime < 0){ finalTime = finalTime + 24 }
}
else {
if (finalTime > 12){ finalTime = (finalTime - 12)+" PM" }
else { finalTime += " AM" }
}
return finalTime.toString();
}
With my CET timezone, calling new Date().getLocalTime('24') will return "10" and calling new Date().getLocalTime() (without parameters or a parameter that isn't "24") will return "10 AM".
Time Conversion Site to check timezones
This function is a reasonable first start, but would not cope with countries like India which have a time offset of x.5 hours (x hours + 30mins). Unfortunately you cannot just divide by 60 like that.
I am new to JavaScript but need to run a check to make sure it is daylight. I am using yahoo's weather API to pull sunrise and sunset. I'm just a little confused as to the best approach for comparing its results to the current time.
I am confused because it returns a time like sunset: '9:01 pm'. bsince there is a PM it is text. I can't think of a good way to compare it to the current time... RegExp, then convert to an integer maybe?
What would be the best approach to this, and why (sorry I'm trying to learn)?
Thanks in advance for any help.
Create a new Date() with the info from yahoo's api, then compare Date.now() with sunsetDate.getTime() and sunriseDate.getTime().
Passing today's date in mm/dd/yyyy format with the time as '9:01 pm' to the Date constructor will give you a valid date.
var today = new Date();
today = [today.getMonth()+1, today.getDate(), today.getFullYear()].join('/');
var yahooSunrise = '5:45 am';
var yahooSunset = '9:01 pm';
var sunrise = new Date(today + ' ' + yahooSunrise).getTime();
var sunset = new Date(today + ' ' + yahooSunset).getTime();
var now = Date.now();
var isDaylight = (now > sunrise && now < sunset);
This would work with something like this, but maybe you might need to change the timings to suite a particular climate:
function getNow() {
var now = new Date
if (now.getHours() < 5) { return "Could be still dark";}
else if (now.getHours() < 9) {return "Definitely day time";}
else if (now.getHours() < 17) { return "Definitely day time"; }
else {return "It gets dark now";}
}
alert(getNow());
One quick approach is to turn both the current time of day and the time you get back from yahoo into the value "minutes since the beginning of the day."
For example, if Yahoo gives you 9:01pm, use the pm to turn the time into 21:01. That is
21*60 + 1 = 1260 + 1 = 1261 minutes since the beginning of the day
Do this for both sunrise and suset. Then get the current time with
new Date()
and do the same kind of thing.
Then just do integer comparisons!
Hope that helps.
This sounds like a good candiidate for a regular expression on the data you get back from the service.
Something like (\d{1,2}):(\d{2})\s(AM|PM) will give you 3 capture groups.
1: The hour (1 or 2 digits)
2: The Minute (2 digits)
3: Either string "AM" or "PM"
You can then use these to parse out the actual time as integer hour and minute to compare to the current time.
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;
}