Laravel Carbon - Reloading Current Time - javascript

I could not find any document in relation to what I am trying to solve, hence I am asking it here.
My controller pulls a Carbon Date using this:
$utctime = Carbon::now()->toTimeString();
That code allows me to display the UTC time on my page. The problem comes in the fact that Carbon only loads the time once (on page load) and it stays at that time. What I want is to Carbon to display the real-time and not require the page to reload.
I am guessing it might not be possible the update the time, as Carbon is not front-end? If so, how would you go about making the time update every second instead of it not updating at all? - Maybe there is something for the front-end that I can use?

Adding a basic ticking clock in Javascript is fairly straightforward:
<div id="time"></div>
<script type="text/javascript">
function showTime() {
var date = new Date(),
utc = new Date(Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds()
));
document.getElementById('time').innerHTML = utc.toLocaleTimeString();
}
setInterval(showTime, 1000);
</script>
This would be entirely front-end based, and ensure there isn't a "jump" between the initially rendered server-time and the user's local time.

You can use moment.js, you can also define the timezone or display UTC time
moment.utc().format();
https://momentjs.com/docs/
https://momentjs.com/timezone/docs/

Related

How to shift fullcalendar's display time by several minutes

This could be an embarrassingly easy question but I am new to Moment.js and fullcalendar.
The goal: Get fullcalendar to operate on a Moment/DateTime that is a few minutes offset from local computer time.
The rationale:
We want to synchronize the display time and nowIndicator with the old clocks in a building as opposed to the desktop's time.
Tried so far:
// Get current offset:
var localOffset = moment().utcOffset();
// Shift by 7 minutes for illustration
localOffset -= 7;
// Set new offset for moment
moment().utcOffset(localOffset);
alert(moment().utcOffset());
As of now it prints back the original UTC offset and the nowIndicator matches my system clock. This is using Moment.js 2.19.0.
Thanks for looking.
moment().utcOffset() is creating a new moment with the default offset. It has nothing to do with the object you previously set an offset on. momentJS works using individual objects which are instantiated by using the moment() constructor. It's not a static or global thing.
What you need to do is work with the moment object which you set the offset on:
var offsetMoment = moment();
offsetMoment.utcOffset(localOffset);
alert(offsetMoment.utcOffset());
ADyson's answer cleared the misconception about a moment object and its scope.
To answer the original problem of shifting FullCalendar's time by an arbitrary amount, use the 'now' option when initializing:
// Get current time as moment object and add 7 minute offset
var shiftedTime = moment().add(7, 'minutes');
// Set 'now' option in calendar initialization to new moment object
$('#calendar').fullCalendar({
// put your options and callbacks here
now: shiftedTime,
defaultView: 'agendaDay',
nowIndicator: true
});
The display of the calendar and the now indicator will be shifted 7 minutes relative to local machine time.

How to display Current time of Dallas and australia

I'm trying to display current time of Dallas and Australia and I have come up with the Code,but it's not working . I'm completely new to Java script and Java here is my code , please help me out in achieving this
<script>
var now = new Date();
var now_utc = now.getUTCHours()-6+":"+ now.getUTCMinutes()+":"+ now.getUTCSeconds()
document.getElementById("inner1").innerHTML+=now_utc;
var aus= new Date();
var aus_time= aus.getUTCHours()+11
document.getElementById("inner2").innerHTML+=aus_time;
</script>
I want to display Current time of Dallas,London,Australia.
Thanks you all.
As once was pointed out by an Apple Engineer: never ever do calendar calculations by yourself. There are tons of small and large pitfalls that most people are unaware of and thus are not taking into account.
If you need an accurate depiction of the (current) time in another Timezone there is no other way then use a library that has all the information regarding Timezones and its peculiarities.
If you do not care about being exact every day of the year then this might be overkill but you have to decide for yourself.
For Javascript there exists the https://github.com/mde/timezone-js library, which itself uses the Olsen Database (https://en.wikipedia.org/wiki/Tz_database).
You have to download the Timezone-Infos and provide them along your source code. Then you can do all that TZ-related calculations/
// 'now' in the Timezone of Chicago (Central Time, should be equal to that of Dallas)
var dt_chicago = new timezoneJS.Date('America/Chicago');
// 'now' in London
var dt_london = new timezoneJS.Date('Europe/London');
// 'now' in Brisbane - you should look up which timezones
// there are in Australia and which you want to display
var dt_brisbane = new timezoneJS.Date('Australia/Brisbane');
I just found out that there is another library http://momentjs.com/timezone/ but I have not used it yet so I may not recommend or advise against using it.
The below piece of code will calculate the current time of any specific time zone. Just pass the time zone of any specific country it will show the current time.
function calcTime(city, offset) {
var d = new Date();
var utc = d.getTime() - (d.getTimezoneOffset() * 60000);
var nd = new Date(utc + (3600000*offset));
return "The local time for city"+ city +" is "+ nd.toLocaleString();
}
console.log(calcTime('Dhaka', '+6.0')));
console.log(calcTime('Australia', '+11.0')));
You use now variable break your script.On live var aus_time you forget semicolon at this line.
As #Traktor53 said in comment AU have multiple timezone.
Your code is OS dependent you will check after change your system time.you will get wrong time. Its better way to use google time API.
function gettz(){
var dnow = new Date();
var dnow_utc = dnow.getUTCHours()-6+":"+ dnow.getUTCMinutes()+":"+ dnow.getUTCSeconds()
document.getElementById("inner1").innerHTML+=dnow_utc;
var aus= new Date();
var aus_time= aus.getUTCHours()+11;
document.getElementById("inner2").innerHTML+=(aus_time);
return;
}
</script>

JavaScript Date does not reflect system time change in Google Chrome

Implementing html+js clock timer (jsfiddle sample) and I found problem when changing operating system time backward and then forward.
Lets have this html:
<div id="time">-</div>
And JS code:
var time = document.getElementById('time');
function iteration() {
time.innerHTML = new Date().toString();
}
setInterval(iteration, 100);
Lets say you started page at 2:22PM. Label display correct time.
Now change operating system local time backward 1 hour to 1:22PM, now JS new Date() correctly returns changed time 1:22PM.
Next change operating system local time forward to actual date - 2:22PM, and now JS new Date() does not return 2:22PM but old 1:22PM. So it seems to me that it does not handle correctly changes to local system time (forward only?).
Seems to be problem only in Google Chrome (37.0.2062.124 m (64-bit)).
In Internet Explorer and Firefox, JS new Date() return correct value.
Update: Does anyone know how to 'fix' this for Google chrome using JS code?

jQuery Countdown - Daily Countdown, with secondary countdown as well?

1. Daily Countdown
I'm trying to use Keith Wood's jQuery countdown plugin (http://keith-wood.name/countdownRef.html) in order to create a page of daily countdowns. E.g.:
A - counts down to 07:00 each day
B - counts down to 09:00 each day
C - counts down to 11:00 each day
I'm doing in a fairly hacky way:
var foo = new Date();
foo.setHours(11)
foo.setMinutes(0)
foo.setSeconds(0)
$('#fooCountdown').countdown({until: foo});
Basically, I just create a new Date object which defaults to now, then set the time to the time I want for today.
However, this is pretty hacky, and also it doesn't reset at the end of the day - once the new day ticks over, it's still counting down to the time on the previous day.
Is there a cleaner or better way of doing daily countdowns with this plugin?
2. Secondary Countdown
Secondly - I also want each countdown, when it expires, to count down to a second later time that day.
E.g. for A - once it reaches 07:00, it then starts counting down to 15:00 for that day.
I'm doing this using the onExpiry function:
$('#officeCountdown').countdown({until: officeOpens, onExpiry: OfficeOpen, alwaysExpire: true});
...
function OfficeOpen() {
$('#officeCountdown').countdown('option', {until: officeCloses, onExpiry: OfficeClose, alwaysExpire: true});
}
function OfficeClose() {
alert('Office has closed')
}
The first part - counting down down until officeOpen seems to work.
However, the second part - counting down until OfficeClose doesn't - it seems to always start counting down the difference between officeOpens and officeCloses, instead of using the current time - and also, the function OfficeCLose never seems to trigger.
Any thoughts?
I would suggest you use the excellent Datejs plugin for creating/handling dates.
(read the getting-started and the docs because it is really extensive)
This way you could do
$('#fooCountdownA').countdown({
until: Date.today.set({hour:7})
});
$('#fooCountdownB').countdown({
until: Date.today.set({hour:9})
});
$('#fooCountdownC').countdown({
until: Date.today.set({hour:11})
});
As for the countdown, the plugin does not seem to be friendly to re-using countdowns..
Perhaps you are better off creating dummy elements and inserting them in the dom to hold the countdown, and destroying them on expiry..

Javascript countdown and timezone and daylight saving time issues

Our team are having big issues with the JQuery countdown and we really need some help.
Initially, we had some ScriptSharp code that does this
JQueryCountdownOptions opts = new JQueryCountdownOptions();
opts.Layout = "<ul class=\"group\"> <li>{dn} <span>{dl}</span></li> <li>{hn} <span>{hl}</span></li> <li>{mn} <span>{ml}</span></li> <li>{sn} <span>{sl}</span></li> </ul>";
opts.Until = Number.ParseInt(timeLeft);
jQuery.Select("#countdownclock").Plugin<JQueryCountdown>().Countdown(opts);
jQuery.Select("#countdownclock").Show();
jQuery.Select("#bidBox").RemoveAttr("disabled");
What we noticed is that this uses the client's clock to countdown from. So, if the client decided to change his time to 5 hours ahead then the countdown would be 5 hours off.
To fix this we introduced some more code
In the view:
$(function () {
var expires = new Date(#year, #month, #day, #hours, #minutes, #seconds);
$('#clockDiv').countdown({ until: expires, timeZone: null, serverSync: serverTime, onTick: serverTime, tickInterval: 60 });
function serverTime() {
var time = null;
$.ajax({ url: '/Auction/SyncServerTime',
async: false, dataType: 'json',
success: function (result) {
time = new Date(result.serverTime);
}, error: function (http, message, exc) {
time = new Date();
}
});
return time;
}
});
In the controller
public JsonResult SyncServerTime()
{
var result = new JsonResult
{
Data = new
{
serverTime = DateTime.Now.ToString("MMM dd, yyyy HH:mm:ss zz")
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
return result;
}
This code ensures that no matter what the user sets his clock to the countdown timer will periodically sync to the server's time. Problem solved.
The only issue is that we have come up with other issues.
The problem is that when users are in different timezones then the countdowns of those users are different depending on the timezone offset that their timezone has. We have tried changing all sorts of parameters and still are having issues. To make matters worse if my timespan straddles a date when daylight saving time is applied then things go awry again, both for those in the same timezone and those in different ones. We have experimented with different code and parameters so the above is just what I did and is different from what my esteemed colleagues tried. What I am asking is surely, someone somewhere out there must have had a requirement to
Write a countdown that is independent of client time and based on server time.
Shows the same number of days, hours, minutes, seconds remaining no matter what timezone a user is in
Shows the same number of days, hours, minutes, seconds remaining for a user whose time will change in this period because of DST to user whose time will not change in this period because of DST
Shows the actual number of days, hours, minutes and seconds remaining for a user whose time will change in this period because of DST.
We cannot be the only people who have ever had this issue, surely. It cannot be this hard. Does anyone know a solution?
Thanks,
Sachin
I haven't dealt with the same scenarios personally, but seeing Date, timezone issues etc. pop up automatically triggers thoughts about some potential issues stemming from the use of local date objects as opposed to UTC date objects.
IMO, things are simply better off if all computation, serialization of dates only worked in the UTC space, and finally when it comes to present a date from a user, it is converted to local or appropriate time zone depending on the scenario. On the flip-side, the user enters local or some time zone relative entry, and immediately that is converted to UTC as the internal representation. This avoids all sorts of confusion across different layers/tiers of the app.
Its not really a solution to your specific problem, but perhaps something to consider that could lead to one.

Categories

Resources