开发者

JavaScript time question

开发者 https://www.devze.com 2023-03-21 13:34 出处:网络
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 comparin

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 a开发者_开发百科ny 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消