Advice needed: Use server time or user machine's time? - javascript

I would like to make a page that greets the user with the classic "good morning/evening", depending on the time of the day. However, I understand that I can't just get the server time because if, say, a user in Japan viewed the page, it might receive a "good afternoon" at 5AM, which is obviously not correct :)
Can I get the time in the user's machine using PHP/JS, and if so, what function should I look at? Also, if JS is needed, how can I detect whether the user has a script blocker in place?
Sorry for the noobish questions, I am just starting to learn about web programming. Any help will be greatly appreciated. :)
Cheers!
- jfabian

PHP runs server side so it will only return the server time I believe.
Something like this in Javascript might work:
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10)
minutes = "0" + minutes
document.write("<b>" + hours + ":" + minutes + " " + "</b>")

You can get the user's timezone in javascript by using:
new Date().getTimezoneOffset() * -1

My suggestion would be to have your PHP page return UTC time e.g. with gmdate()
see get UTC time in PHP with UTC time you don't have to worry so much about things like daylight savings time, etc.
Then in your javascript you would determine the timezone offset of the user. You could use
new Date().getTimezoneOffset()
or for more advanced timezone stuff you may use a javascript library, see How to get user timezone using jquery? for some ideas.

Related

Get user local time by ip address with JavaScript?

I'm trying to get time of day for someone visiting my site. Seems easy enough, but the tricky part is that people may be traveling from other timezones and not changing their system clock. Using the below:
var d = new Date();
var currentTime = d.getHours();
console.log( currentTime );
if(currentTime < 12){
var tod = "morning";
}else if(currentTime >= 12 && currentTime <= 17){
var tod = "afternoon";
}else{
var tod = "evening";
}
document.write("hour of day is: "+currentTime);
console.log("Time of day is: "+tod );
I was able to detect local system time. For example, if my clock says 7:06 AM, then the variable currentTime will be 7. This works based on the system clock. So if I change my time zone to Eastern, currentTime will be 10 instead of 7. The problem is I'd like to detect the time of day where the user is actually sitting at that moment. So if I'm on the East coast and my system clock says 7AM, I still want to show the user a 10. I want to detect the hour of day it actually is where the user is by IP address. I have found a way to collect IP address, but not sure how to use it to get the local time.
If there is another way I am also open to that as well. Thanks.
Some might suggest getting it from the server, but I am using marketing cloud and there does not appear to be a way to do it. I've used the available AmpScript functions and they do not work as I would have expected.
Use any API that will respond with user's timezone. For example this one:
http://ip-api.com/json
And calculate user's time basing on it.

How to get NTP time based on timezone id using javascript with good precision

before was getting time by timezone id using JavaScript this way.
var tz = jstz.determine(); // Determines the time zone of the browser client
var format = 'YYYY/MM/DD HH:mm:ss ZZ';
alert(moment.tz('Europe/London').format(format));
OR
alert(moment.tz(tz.name()).format(format));
i was using two library one for getting timezone id from client browser and other one to get date & time based on timezone id. those two libraries are
<script type="text/javascript" src="Scripts/jstz.min.js"></script>
<script src="Scripts/moment.min.js" type="text/javascript"></script>
<script src="Scripts/moment-timezone-with-data-2010-2020.min.js" type="text/javascript">
but the problem is moment.js was giving time based on user pc date time setting. so if user pc date time is wrong then moment.js will return wrong date time. so i was looking for a way like how to get date & time by timezone id following ntp protocol.fortunately i got a solution from this url
their code as follows
// Get London time, and format it:
getTime('Europe/London', function(time){
var formatted = time.getHours() + ':'
+ time.getMinutes() + ':'
+ time.getSeconds();
alert( 'The time in London is ' + formatted );
});
$.getTime = function(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz='
+ zone + '&callback=?';
$.getJSON(url, function(o){
success && success(new Date(o.datetime), o);
});
};
how far i understand the above code that it will call time.json and pass timezone id and response will back a new date and time based on timezone id.
i have one question that
1) please tell me someone that above js routine will return right date and time based on timezone id?
2) what about latency is there. suppose i made call to time.json and got the response back after 10 sec may be due to slow internet or any other reason. in this situation how could i get correct date & time.
so guide me what i need to do to always get correct time with date if response back after few sec or minute. also discuss what other best way out there to get NTP date & time using javascript. looking for guidance.
he main issue is latency...if i get response back after few sec or minute then how could i re-calculate time to make it accurate for latency or slow response problem.....please guide me someone. thanks

In Javascript / NodeJS return current date adjusting for timezone, then find UTC equivalent of user's time at 6am

Sorry if the title is a little convoluted. I'm bashing my head against the floor with times in NodeJS / Javascript. I can get the current UTC time like this:
var currentTime = Date.now();
I can get the current time for a user who is, for example, in the -3 timezone like this:
var offsetTime = Date.now() + (numTimeZone * 3600000);
But how do I get the local user time at, say, 6am, converted to UTC?
Practical application:
What I'm trying to do is create an auto-emailer which sends an email to a user at 6am in their local time. My server is in one timezone and they will be in another, so I'm trying to standardise it against UTC so every minute I can set my server to check the currentUTC time, then check what the user's 6am time is converted to UTC (local6am), and if the currentUTC > local6am then an email should be sent.
What's the best way to achieve this? Preferably without using a library if possible.
Utc to Local
moment.utc('2014-02-19 05:24:32 AM').toDate();
Local to utc
Read this documentation.
MomentJS is parsing the date as a locale date-time. If no hour is given, it is assuming midnight.
Then, you convert it to UTC, so it is shifted, according to your local time, forward or backwards. If your are in UTC+N, then you will get the previous date.
moment(new Date('02-19-2014')).utc().format("YYYY-MM-DD HH:mm").toString()
moment(new Date('02-19-2014 12:00')).utc().format("YYYY-MM-DD HH:mm").toString()
(or)
You can try this:
moment.utc('07-18-2013', 'MM-DD-YYYY')
moment.utc('07-18-2013', 'MM-DD-YYYY').format('YYYY-MM-DD')
You do not need to call toString explicitly.

Javascript - How to return the time where I live?

So I'm doing codecademy and the current section I'm on wants you to return the current time and display different messages depending on the current time.
You could pass with any time but I'd rather configure it to be my timezone and even extra if anyone knows, the time zone that the person accessing the web page is in.
Currently I have this.
var d = new Date();
console.log(d);
This prints GMT time.
What I'd like is GMT +10.
I knows there's a function that returns your timezone
var n = d.getTimezoneOffset();
But I'm not too sure as to how I get this to interact with the Date function so that it prints the time in this timezone.
Thanks!
Regards,
Matt
SOLVED: Was a bug in codecademy.
Use the Date methods.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
For example, d.getDate() will return the local date, whereas d.getUTCDate() will return the GMT-based date.

Calculate amount of time until the next hour

I'm working on a busing website project and the buses run every hour. I'm having trouble creating a widget that finds the time between now and the next hour, so that it is clear when the next bus will run. My client requires that it is in javascript. Any suggestions?
Thanks in advance.
To know exactly the miliseconds from now to the next hour:
function msToNextHour() {
return 3600000 - new Date().getTime() % 3600000;
}
Please note that this will strictly tell you how many milliseconds until the NEXT hour (if you run this at 4:00:00.000 it will give you exactly one hour).
function getMinutesUntilNextHour() { return 60 - new Date().getMinutes(); }
Note that people who's system clocks are off will miss their bus. It might be better to use the server time instead of the time on the client's computer (AKA at least partly a non-client-side-javascript solution).
you have the Date object in Javascript, you could do something like:
var now = new Date();
var mins = now.getMinutes();
var secs = now.getSeconds();
var response = "it will be " + (60 - mins - 1) + " minutes and " + (60 - secs) + " seconds until the next bus";
of course you will have to work more on those calculations, but that's how you work with time in javascript
Either of the other two answers will work well, but are you aware of the docs available to you about all the other nice things date is JS can do for you?
Mozilla Date Docs
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
Lots of answers, a really simple function to get the rounded minutes remaining to the next hour is:
function minsToHour() {
return 60 - Math.round(new Date() % 3.6e6 / 6e4);
}

Categories

Resources