JavaScript time question - javascript

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.

Related

Comparing 2 strings with number values JS

Im trying to check to see if current time is lower than time that is responded from an API. Problem is they are both strings. The API response contains characters such as : and -, so parseInt is not working (at least that's my theory why its not working)
var d = new Date();
var hour = d.getHours();
var minutes = d.getMinutes();
var year = d.getFullYear();
var month = d.getMonth() +1;
var day = d.getDate();
var seconds = d.getSeconds();
var time = year+'-'+month+'-'+day+' '+hour+':'+minutes+':'+seconds;
time returns
"2016-11-7 15:48:2"
API Response is
"2016-11-07 20:06:00"
I have confirmed they are both strings
time < APIresponse
Always returns false
Are there any known solutions? Thanks in advance.
Preface: Timezone
Your current code assumes that the date/time you're getting from the API is in "local time," because you're comparing it with the current date/time in the browser's local timezone. APIs frequently provide date/times in UTC rather than "local" time, so beware of that assumption and double-check it.
If you want to do it at the string level
...you need to ensure when building time that you zero-pad the numbers, so for instance not just 7 for the day of the month, but 07. Then you'll end up with strings that have the fields in a valid comparable order (because the most significant field [year] is first, and the least significant field [seconds] is last), so a lexicographic comparison of the strings is valid.
So for instance, you'd create time like this:
var time = pad(year, 4) + '-' + pad(month, 2) + '-' + pad(day, 2) + ' ' + pad(hour, 2) + ':' + pad(minutes, 2) + ':' + pad(seconds, 2);
...where pad is a function you define that adds as many 0s as needed to ensure the string is as long as the second argument defines.
Then you can do:
if (time < timeStringFromAPI)
Note: If the API's response is giving you the date/time in UTC rather than local time, you'll need to use the UTC version of the accessor functions (e.g., getUTCHours, getUTCFullYear, etc.) rather than the ones you're using, which are for local time.
If you want to do it at the date level
...then you need to convert the date you're getting from the API to a Date. It's almost in a form you can reliable parse on modern browsers,
but not quite; some browsers will parse that string as local time, others as UTC.
If you're sure it's in local time, then the best thing to do is split it into its parts and use the multipart Date constructor:
var parts = timeStringFromAPI.split(/[-:]/);
var apiDate = new Date(
+parts[0], // Year
+parts[1] - 1, // Month
+parts[2], // Day
+parts[3], // Hours
+parts[4], // Minutes
+parts[5] // Seconds
);
If you're sure it's in UTC, then you can either do the above but with new Date(Date.UTC(...)) rather than just new Date(...), or you can put the string into the JavaScript date/time format and parse that:
var apiDate = new Date(timeStringFromAPI.replace(" ", "T") + "Z");
That takes the "2016-11-07 20:06:00" and changes it to "2016-11-07T20:06:00Z", which can reliably be parsed on all non-obsolete browsers.
Then you can do
if (new Date() < apiDate) {
try this :
var curDate = new Date();
then compare in this way
if (new Date(yourdate) <= curDate)
{
something...
}
var d1 = "2016-11-7 15:48:2";
var d2 = "2016-11-07 20:06:00";
if (new Date(d1) < new Date(d2)) {
alert('true')
}

How to get the Australian Time Zone using Javascript? (Not JQuery)

I am trying to help a friend to get the Australian Time Zone for the University Assignment and finding difficulty.
Could someone point us in the right direction?
Thank you!
<script>
function Timezone() {
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
document.getElementById("add").innerHTML = currentTimeZoneOffsetInHours;
}
</script>
<p id="add"></p>
You simply use
let AuDate = new Date().toLocaleString("en-US", {timeZone: "Australia/Sydney"});
By looking at your code, looks like you are trying to get the current date and time of an Australian timezone. Lets say you want Australian Eastern Standard Time (AEST) and you want the date displayed how they would in Australia DD-MM-YYYY then do the following:
var timestamp_UTC = new Date();
var readable_timestamp_AEST = timestamp_UTC.toLocaleDateString("en-AU", {timeZone: "Australia/Sydney"}).replace(/\//g, "-") + ' ' + somestamp.toLocaleTimeString("en-AU", {timeZone: "Australia/Sydney"});
"en-AU" is the locales argument which tells the toLocalDateString to display the date as DD-MM-YYYY and the second argument is for options (timeZone is just one such possible option). Info about toLocalDateString function can be found here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
Here is some information about the Date() function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Hope this clears up a few things around getting times and dates from the Date() function.
I think i understand what you mean. But before that i'd like to make 2 points:
1: The Timezone() function should be called somewhere.
<script>
function Timezone() {
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
document.getElementById("add").innerHTML = currentTimeZoneOffsetInHours;
}
Timezone();
</script>
2: The convention usually is that methods start with a lower case letter. Maybe updateTimezone() would be more appropriate.
Your question can be interpreted in 2 ways now:
you want your timezone's offset in hours and for this the code above should work. getTimezoneOffset() is the way to go.
you want a human readable name of your timezone, as you can see on my site currentmillis.com (in my case it says GTB Summer). You can look in my source code to see how i achieve this:
var s = date.toString();
var iOfP = s.indexOf('('); // index of parenthesis
if (iOfP < 0) {
s = s.substring(s.lastIndexOf(' ') + 1);
} else {
s = s.substring(iOfP+1, s.length-1);
}
if (s.length > 4 && s.lastIndexOf(" Time") == s.length-5){
s = s.substring(0, s.length-5);
}
timezoneM.innerHTML = s;
This works because when you call toString() on the date the result should contain the full name of your timezone: w3schools.com/jsref/jsref_tostring_date.asp

Convert 1 AM PST to local time in JavaScript?

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.

the closest Sunday before given date with JavaScript

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;
}

Javascript Date.UTC() function is off by a month?

I was playing around with Javascript creating a simple countdown clock when I came across this strange behavior:
var a = new Date(),
now = a.getTime(),
then = Date.UTC(2009,10,31),
diff = then - now,
daysleft = parseInt(diff/(24*60*60*1000));
console.log(daysleft );
The days left is off by 30 days.
What is wrong with this code?
Edit: I changed the variable names to make it more clear.
The month is zero-based for JavaScript.
Days and years are one-based.
Go figure.
UPDATE
The reason this is so, from the creator of JavaScript, is
JS had to "look like Java" only less so, be Java's dumb kid brother or boy-hostage sidekick. Plus, I had to be done in ten days or something worse than JS would have happened.
http://www.jwz.org/blog/2010/10/every-day-i-learn-something-new-and-stupid/#comment-1021
As Eric said, this is due to months being listed as 0-11 range.
This is a common behavior - same is true of Perl results from localtime(), and probably many other languages.
This is likely originally inherited from Unix's localtime() call.
(do "man localtime")
The reason is that days/years are their own integers, while months (as a #) are indexes of an array, which in most languages - especially C where the underlying call is implemented on Unix - starts with 0.
It's an old question but this is still a problem today (or a feature as some might say - and they are wrong).
JS is zero-based month, why? Because.
That means the months range from 0-11 (only the months, the others are normal)
How can you fix this? Add a month, obviously, BUUUUT:
Don't do this :
let date: Date = new Date();
date.setMonth(date.getMonth() + 1);
Why you might ask? Because it won't work as expected, Date in JS is terrible.
You have to make a ... let's call it not so beautiful function to translate the JS date to a normal date
formatJsDateToNormalDate(Date date): string | null {
if(date !== null) {
const realMonth: number = date.getMonth() + 1;
let month: string = (realMonth < 10) ? '0' + realMonth : String(realMonth);
let day: string = (date.getDate() < 10) ? '0' + date.getDate() : String(date.getDate());
return [date.getFullYear(), month, day].join('-');
} else {
return null;
}
Again, if you ask me this is the equivalent of hammering a screw, it's not the right way, but there is no right way here, it's a bug that has been going on for 27 years and more to come.
date1 = new Date();
//year, month, day [, hrs] [, min] [, sec]
date1 = new Date.UTC(date1.getFullYear(),date1.getMonth()+1,date1.getDate(),date1.getHours(),date1.getMinutes(),date1.getSeconds());
date2 = new Date();
date2 = date2.getTime();
alert(date1)
alert(date2)

Categories

Resources