C# WebSockets and JavaScript sync time

I have events which occur in a C# based application which run on a timer. However, I can’t seem to ever get both server and clients time to sync with one another to show a count down to which the event is going to end.

I am used web sockets to communicate with the client. Here are some of the things which I have done in attempt to achieve a sync but either the client or server is out of sync as timer either finishes before or after rarely ever at the same time.

Sending time in second

I send a simply message like start-timer;100 which triggers 100 seconds. Then I use something like this

function setTimer(type, expire)
            if(cycleTimers[type] == undefined) {
                cycleTimers[type] = {};

            var d = new Date();
            d.setSeconds(d.getSeconds() + expire);

            cycleTimers[type].time = d;
            if(cycleTimers[type].interval != undefined) {

            cycleTimers[type].interval = setInterval(function() {

                var time = Math.abs((new Date() - cycleTimers[type].time) / 1000);

                var minutes = ("00" + Math.floor(time / 60)).slice(-2);
                var seconds = ("00" + Math.floor(time % 60)).slice(-2);

                $(".timer-cycle").html(minutes + ":" + seconds);

                if(time <= 0) {
            }, 500);

The reason for type, is that in the end I would like to run multiple timers and show the time left on the clients screen. However, for purpose of this example it isn’t needed.

Time in seconds with interval

I have send the time in seconds above but instead of converting it to a date I attempted to just use an interval of 1000 and decrease the seconds remaining by one on each cycle. This didn’t work either.

Unix time stamp

I also attempted to convert date time from c# to a timestamp and send it to client for expire time but they were completely different to one another.


this.ExpireTime = DateTime.UtcNow.AddSeconds(Seconds);

I run a task which executes every 500ms to check if this.Expired is less than current date if so then stop cycle. This works fine on emulator as I write to console the time at each tick.

Source: stackoverflow-javascript

PHP DateInterval diff wrong calculates begin and end of interval

I have a strange problem with DateIntervals.

For my client I’m writing some time basis report. Based on given date I have to detect valid date interval, move the current time pointer to it, and then make some series of interval till the end.

I have a problem with detection of start and end of given interval.
Let’s see this in the code

I have this intervals:

const TIME_INTERVAL_5_MINUTES  = '5 minutes';
const TIME_INTERVAL_30_MINUTES = '30 minutes';

const TIME_INTERVAL_1_HOUR   = '1 hour';
const TIME_INTERVAL_6_HOURS  = '6 hours';
const TIME_INTERVAL_12_HOURS = '12 hours';

const TIME_INTERVAL_1_DAY   = '1 day';
const TIME_INTERVAL_1_WEEK  = '1 week';

    self::TIME_INTERVAL_5_MINUTES  => 300,
    self::TIME_INTERVAL_30_MINUTES => 1800,
    self::TIME_INTERVAL_1_HOUR     => 3600,
    self::TIME_INTERVAL_6_HOURS    => 21600,
    self::TIME_INTERVAL_12_HOURS   => 43200,
    self::TIME_INTERVAL_1_DAY      => 86400,
    self::TIME_INTERVAL_1_WEEK     => 604800,
    self::TIME_INTERVAL_1_MONTH    => -1, // month has a special treatment, won't be the subject here.

Now I want to calculate the time interval border based on given time:

private function calculateNearestRange(DateTimeImmutable $time, $rangeLength, $mode)
    $rangeMiddlePointLength = (int)($rangeLength / 2);

    // The modulo calculates should contain only the time 'inside'
    // date interval. So if I have 12h interval (which starts at
    // each day on 00:00 and 12:00) when I have time 22:51, it
    // should be equal (in seconds) 10h and 51m, but mostly it is 
    // not. So source of wrong calculations probably is this line.
    // And I don't know what I'm doing wrong
    $remainingPart          = $time->getTimestamp() % $rangeLength;

    $rangeStart       = $time->sub(new DateInterval("PT{$remainingPart}S"));
    $rangeEnd         = $time->add(new DateInterval("PT{$rangeLength}S"));
    $rangeMiddlePoint = $rangeStart->add(new DateInterval("PT{$rangeMiddlePointLength}S"));

    switch ($mode) {
        case static::MODE_NEXT:
            return $rangeEnd;

        case static::MODE_PREVIOUS:
            return $rangeStart;

        case static::MODE_NEAREST:
            return $time >= $rangeMiddlePoint
                ? $rangeEnd
                : $rangeStart;

Everything is fine for intervals: 5min, 30min, 1hour. But when the next comes it starts to calculate bad things.

For the given data sets:

    'Interval length', 
    'time parameter in calculateNearestRange method'
    'expected output'

'6hours: MODE_PREVIOUS'      => [
    new DateTimeImmutable('2017-03-03 11:51'),
    new DateTimeImmutable('2017-03-03 06:00'), // But returns '2017-03-03 06:00'
'6hours: MODE_NEXT'          => [
    new DateTimeImmutable('2017-03-03 06:11'),
    new DateTimeImmutable('2017-03-03 12:00'), // But return '2017-03-03 07:00'
'12hours: MODE_PREVIOUS'     => [
    new DateTimeImmutable('2017-03-03 11:51'),
    new DateTimeImmutable('2017-03-03 00:00'), // But returns '2017-03-03 01:00'

The longer interval comes, the bigger differences comes.

When I use calculator (on timestamps), I have the save values as my PHP code have, so I think problem is somewhere with the precission of methodology ? Have any of you meet similar problem before and know some tips how to solve it?

Source: stackoverflow-php

Sort array of datesTime

I have a array of objects that have a property of date adn time, and im trying to sort by desc or asc, but it doesnt work, it gets all mix up da array.

My code:

var myDateTime = [
{date: "2016-06-08 18:10:00"},
{date: "2016-04-26 20:01:00"},
{date: "2017-02-06 14:38:00"},
{date: "2017-01-18 17:30:21"},
{date: "2017-01-18 17:24:00"},

var sortIt = myDateTime.sort(function(a, b) {
                    return new Date( a.date ) < new Date( b.date );

Source: stackoverflow-javascript