System.DateTime.AddMilliseconds(double)

Here are the examples of the csharp api System.DateTime.AddMilliseconds(double) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

782 Examples 7

19 View Source File : DateTimeExtensions.cs
License : MIT License
Project Creator : 1100100

public static DateTime ToDateTime(this long timestamp, TimestampUnit timestampUnit = TimestampUnit.Second, DateTimeKind dateTimeKind = DateTimeKind.Local)
        {
            var time = timestampUnit == TimestampUnit.Second
                ? Jan1St1970.AddSeconds(timestamp)
                : Jan1St1970.AddMilliseconds(timestamp);
            return dateTimeKind == DateTimeKind.Local ? time.ToLocalTime() : time;
        }

19 View Source File : Converter.cs
License : MIT License
Project Creator : 4egod

public static DateTime FromTwitterTimestamp(this long timestamp)
        {
            DateTime result = new DateTime(1970, 1, 1);
            result = result.AddMilliseconds(timestamp);
            return result;
        }

19 View Source File : OtherExpressions.cs
License : MIT License
Project Creator : 71

[Fact]
        public void ShouldLockExecution()
        {
            object syncRoot = new object();
            Expression syncRootEx = syncRoot.AsExpression();

            Expression sleep = X.Express<Action>(() => Thread.Sleep(2000));

            Action compiledAction = Expression
                .Lambda<Action>(X.Lock(syncRootEx, sleep))
                .Compile();

            Task task = Task.Run(compiledAction);

            // Sleep to make sure the task has the time to start running
            while (task.Status != TaskStatus.Running)
                Thread.Sleep(50);

            DateTime beforeEntering = DateTime.Now;

            lock (syncRoot)
                DateTime.Now.ShouldBeGreaterThan(beforeEntering.AddMilliseconds(1000));
        }

19 View Source File : PropertyTests.cs
License : MIT License
Project Creator : 71

public static DateTime Trim(DateTime dt) => dt.Millisecond == 0 ? dt : dt.AddMilliseconds(-dt.Millisecond);

19 View Source File : RecurringQueue.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<bool> Publish<T>(string uniqueId, T t, int delayMin, int delayMax = 0)
        {
            var channel = t.GetType().Name.ToLower();
            var key = $"{queueName}_{channel}";
            Random rnd = new Random();
            var delay = delayMax > delayMin ? rnd.Next(delayMin, delayMax) : delayMin;
            if (delay < 2000)
            {
                delay = 2000;
            }
            var message = new QueueData<T>
            {
                DelayMin = delayMin,
                DelayMax = delayMax,
                Data = t,
                DelayTime = DateTime.Now.AddMilliseconds(delay)
            };


            var isSuccess = await _redisDb.HashSet(key, uniqueId, message);
            if (isSuccess)
            {
                await RemoveCache(channel);
            }
            return isSuccess;
        }

19 View Source File : RecurringQueue.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<Dictionary<string,T>> Subscribe<T>()
        {
            var list = new Dictionary<string, T>();
            var channel = typeof(T).Name.ToLower();
            var key = $"{queueName}_{channel}";
            var dic = await _redisDb.HashGetAll<QueueData<T>>(key);
            if (dic == null || dic.Count == 0)
            {
                return default;
            }

            bool hasChange = false;
            Random rnd = new Random();
            foreach (var item in dic)
            {
                var uniqueId = item.Key;
                var itemValue = item.Value;
                if (itemValue.DelayTime.Subtract(DateTime.Now).TotalMilliseconds > 0)
                {
                    //没到时间
                    continue;
                }


                var delay = itemValue.DelayMax > itemValue.DelayMin ? rnd.Next(itemValue.DelayMin, itemValue.DelayMax) : itemValue.DelayMin;
                if (delay < 2000)
                {
                    delay = 2000;
                } 
                //下次消费时间
                itemValue.DelayTime = DateTime.Now.AddMilliseconds(delay);

                if (!list.ContainsKey(uniqueId))
                {
                    list.Add(uniqueId, itemValue.Data);
                }
                await _redisDb.HashSet(key, uniqueId, itemValue);
                hasChange = true;
            }

            if (hasChange)
            {
                await RemoveCache(channel);
            }

            return list;
        }

19 View Source File : TimestampConverter.cs
License : MIT License
Project Creator : aabiryukov

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader == null) throw new ArgumentNullException(nameof(reader));

            var t = Convert.ToInt64(Math.Round(decimal.Parse(reader.Value.ToString(), CultureInfo.InvariantCulture)));
            return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(t);
        }

19 View Source File : ConnectClient.cs
License : Apache License 2.0
Project Creator : AantCoder

private byte[] ReceiveBytes(int countByte)
        {
            //if (!Loger.IsServer) Loger.Log("Client ReceiveBytes " + countByte.ToString() + ", " + Client.ReceiveBufferSize);
            //результат
            byte[] msg = new byte[countByte];
            //сколько уже считано
            int offset = 0;
            //буфер результата
            byte[] receiveBuffer = new byte[Client.ReceiveBufferSize];
            //кол-во считано байт последний раз
            int numberOfBytesRead = 0;
            //длина передаваемого сообщения (принимается в первых 4 байтах (константа Int32Length))
            int lenghtAllMessageByte = countByte;
            var timeOut = DateTime.UtcNow.AddMilliseconds(SilenceTime);

            while (lenghtAllMessageByte > 0)
            {
                int maxCountRead = receiveBuffer.Length;
                if (maxCountRead > lenghtAllMessageByte) maxCountRead = lenghtAllMessageByte;


                //numberOfBytesRead = ClientStream.Read(receiveBuffer, 0, maxCountRead);

                var receiveId = Interlocked.Increment(ref ReceiveId);
                ClientStream.BeginRead(receiveBuffer, 0, maxCountRead, ReceiveBytescallback, receiveId);

                while (!ReceiveReady.ContainsKey(receiveId)
                    && timeOut > DateTime.UtcNow)
                    Thread.Sleep(1);

                lock (ReceiveReady)
                {
                    if (ReceiveReady.ContainsKey(receiveId))
                    {
                        var objRes = ReceiveReady[receiveId];
                        if (objRes is Exception) throw (Exception)objRes;
                        numberOfBytesRead = (int)ReceiveReady[receiveId];
                        ReceiveReady.Remove(receiveId);
                    }
                    else
                        throw new ConnectSilenceTimeOutException();
                }

                if (!Client.Client.Connected)
                {
                    throw new ConnectNotConnectedException();
                }


                if (numberOfBytesRead == 0)
                {
                    if (timeOut < DateTime.UtcNow)
                        throw new ConnectSilenceTimeOutException();
                    Thread.Sleep(1);
                }
                else
                {
                    timeOut = DateTime.UtcNow.AddMilliseconds(SilenceTime);
                    Buffer.BlockCopy(receiveBuffer, 0, msg, offset, numberOfBytesRead);
                    offset += numberOfBytesRead;
                    lenghtAllMessageByte -= numberOfBytesRead;
                }
            };

            return msg;
        }

19 View Source File : WorkTimer.cs
License : Apache License 2.0
Project Creator : AantCoder

private void Do()
        {
            var needSleep = true;
            while (!IsStop)
            {
                if (Pause)
                {
                    Thread.Sleep(1);
                    continue;
                }
                if (needSleep) Thread.Sleep(1);
                needSleep = true;
                try
                {
                    lock (Timers)
                    {
                        if (Timers.Count == 0) continue;
                        var now = DateTime.UtcNow;
                        LastLoop = now;
                        var curIndex = Index;
                        while (true)
                        {
                            var item = Timers[curIndex++];
                            if (curIndex >= Timers.Count) curIndex = 0;
                            if (item.LastRun.AddMilliseconds(item.Interval) < now)
                            {
                                //выполнение
                                item.LastRun = now;
                                DoItem(item.Act);
                                //записываем индекс с которого начнем цикл в следующий раз
                                Index = curIndex;
                                needSleep = false;
                                break;
                            }
                            //если ничего не выполняли, то проверяем, не завешен ли цикл
                            if (IsStop || curIndex == Index) break;
                        }
                    }
                }
                catch
                {
                }
            }

        }

19 View Source File : NetworkSession.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void Update()
        {
            if (isReleased) // Session has been removed
                return;

            if (DateTime.UtcNow - lastCachedPacketPruneTime > cachedPacketPruneInterval)
                PruneCachedPackets();

            for (int i = 0; i < currentBundles.Length; i++)
            {
                NetworkBundle bundleToSend = null;

                var group = (GameMessageGroup)i;

                var currentBundleLock = currentBundleLocks[i];
                lock (currentBundleLock)
                {
                    var currentBundle = currentBundles[i];

                    if (group == GameMessageGroup.InvalidQueue)
                    {
                        if (sendResync && !currentBundle.TimeSync && DateTime.UtcNow > nextResync)
                        {
                            packetLog.DebugFormat("[{0}] Setting to send TimeSync packet", session.LoggingIdentifier);
                            currentBundle.TimeSync = true;
                            currentBundle.EncryptedChecksum = true;
                            nextResync = DateTime.UtcNow.AddMilliseconds(timeBetweenTimeSync);
                        }

                        if (sendAck && !currentBundle.SendAck && DateTime.UtcNow > nextAck)
                        {
                            packetLog.DebugFormat("[{0}] Setting to send ACK packet", session.LoggingIdentifier);
                            currentBundle.SendAck = true;
                            nextAck = DateTime.UtcNow.AddMilliseconds(timeBetweenAck);
                        }

                        if (currentBundle.NeedsSending && DateTime.UtcNow >= nextSend)
                        {
                            packetLog.DebugFormat("[{0}] Swapping bundle", session.LoggingIdentifier);
                            // Swap out bundle so we can process it
                            bundleToSend = currentBundle;
                            currentBundles[i] = new NetworkBundle();
                        }
                    }
                    else
                    {
                        if (currentBundle.NeedsSending && DateTime.UtcNow >= nextSend)
                        {
                            packetLog.DebugFormat("[{0}] Swapping bundle", session.LoggingIdentifier);
                            // Swap out bundle so we can process it
                            bundleToSend = currentBundle;
                            currentBundles[i] = new NetworkBundle();
                        }
                    }
                }

                // Send our bundle if we have one
                // We should be able to execute this outside the lock as Sending is single threaded
                // and all future writes from other threads will go to the new bundle
                if (bundleToSend != null)
                {
                    SendBundle(bundleToSend, group);
                    nextSend = DateTime.UtcNow.AddMilliseconds(minimumTimeBetweenBundles);
                }
            }

            FlushPackets();
        }

19 View Source File : SystemExtensions.cs
License : MIT License
Project Creator : adrenak

public static DateTime ToHumanTime(this long unixTimeStamp) {
            DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            return epoch.AddMilliseconds(Convert.ToDouble(unixTimeStamp));
        }

19 View Source File : SystemExtensions.cs
License : MIT License
Project Creator : adrenak

public static DateTime? ToHumanTime(this string unixTimeStamp) {
            try {
                DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                return epoch.AddMilliseconds(Convert.ToInt64(unixTimeStamp));
            }
            catch {
                return null;
            }
        }

19 View Source File : HCTimeBarNew.cs
License : GNU General Public License v3.0
Project Creator : aduskin

private void UpdateSpeBlock()
      {
         var rest = (_totalOffsetX + _tempOffsetX) % _itemWidth;
         for (var i = 0; i < _speCount; i++)
         {
            var item = _speBlockList[i];
            item.MoveX(rest + (_itemWidth - item.Width) / 2);
         }
         var sub = rest <= 0 ? _speCount / 2 : _speCount / 2 - 1;

         for (var i = 0; i < _speCount; i++)
            _speBlockList[i].Time = TimeConvert(SelectedTime).AddMilliseconds((i - sub) * _timeSpeList[_speIndex]);
      }

19 View Source File : HCTimeBarNew.cs
License : GNU General Public License v3.0
Project Creator : aduskin

private void Update()
      {
         if (_canvreplacedpe == null) return;

         _speBlockList.Clear();
         _canvreplacedpe.Children.Clear();
         _speCount = (int)(ActualWidth / 800 * 9) | 1;

         var itemWidthOld = _itemWidth;
         _itemWidth = ActualWidth / _speCount;
         _totalOffsetX = _itemWidth / itemWidthOld * _totalOffsetX % ActualWidth;
         if (double.IsNaN(_totalOffsetX))
         {
            _totalOffsetX = 0;
         }

         var rest = (_totalOffsetX + _tempOffsetX) % _itemWidth;
         var sub = rest <= 0 || double.IsNaN(rest) ? _speCount / 2 : _speCount / 2 - 1;
         for (var i = 0; i < _speCount; i++)
         {
            var block = new HCSpeTextBlock
            {
               Time = TimeConvert(SelectedTime).AddMilliseconds((i - sub) * _timeSpeList[_speIndex]),
               TextAlignment = TextAlignment.Center,
               TimeFormat = "HH:mm"
            };
            _speBlockList.Add(block);
            _canvreplacedpe.Children.Add(block);
         }

         if (_speIndex == 6)
         {
            SetSpeTimeFormat("HH:mm:ss");
         }

         ShowSpeStr = ActualWidth > 320;
         for (var i = 0; i < _speCount; i++)
         {
            var item = _speBlockList[i];
            item.X = _itemWidth * i;
            item.MoveX((_itemWidth - item.Width) / 2);
         }

         UpdateSpeBlock();
         UpdateMouseFollowBlockPos();
      }

19 View Source File : MinerListExtensions.cs
License : MIT License
Project Creator : AElfProject

internal static Round GenerateFirstRoundOfNewTerm(this MinerList miners, int miningInterval,
            DateTime currentBlockTime, long currentRoundNumber = 0, long currentTermNumber = 0)
        {
            var sortedMiners =
                (from obj in miners.Pubkeys.Distinct()
                        .ToDictionary<ByteString, string, int>(miner => miner.ToHex(), miner => miner[0])
                    orderby obj.Value descending
                    select obj.Key).ToList();

            var round = new Round();

            for (var i = 0; i < sortedMiners.Count; i++)
            {
                var minerInRound = new MinerInRound();

                // The first miner will be the extra block producer of first round of each term.
                if (i == 0)
                {
                    minerInRound.IsExtraBlockProducer = true;
                }

                minerInRound.Pubkey = sortedMiners[i];
                minerInRound.Order = i + 1;
                minerInRound.ExpectedMiningTime =
                    currentBlockTime.AddMilliseconds((i * miningInterval) + miningInterval).ToTimestamp();
                // Should be careful during validation.
                minerInRound.PreviousInValue = Hash.Empty;

                round.RealTimeMinersInformation.Add(sortedMiners[i], minerInRound);
            }

            round.RoundNumber = currentRoundNumber + 1;
            round.TermNumber = currentTermNumber + 1;
            round.IsMinerListJustChanged = true;

            return round;
        }

19 View Source File : BlockMiningService.cs
License : MIT License
Project Creator : AElfProject

private async Task InitialConsensus(DateTime currentBlockTime)
        {
            // InitialAElfConsensusContract
            {
                var executionResult = await _contractStubs.First().InitialAElfConsensusContract.SendAsync(
                    new InitialAElfConsensusContractInput
                    {
                        MinerIncreaseInterval = AEDPoSExtensionConstants.MinerIncreaseInterval,
                        PeriodSeconds = AEDPoSExtensionConstants.PeriodSeconds,
                        IsSideChain = _chainTypeProvider.IsSideChain
                    });
                if (executionResult.TransactionResult.Status != TransactionResultStatus.Mined)
                {
                    throw new InitializationFailedException("Failed to execute InitialAElfConsensusContract.",
                        executionResult.TransactionResult.Error);
                }
            }

            var initialMinerList = new MinerList
            {
                Pubkeys = {MissionedECKeyPairs.InitialKeyPairs.Select(p => ByteString.CopyFrom(p.PublicKey))}
            };
            _currentRound =
                initialMinerList.GenerateFirstRoundOfNewTerm(AEDPoSExtensionConstants.MiningInterval,
                    currentBlockTime);
            _testDataProvider.SetBlockTime(currentBlockTime.ToTimestamp());

            // FirstRound
            {
                var executionResult = await _contractStubs.First().FirstRound.SendAsync(_currentRound);
                if (executionResult.TransactionResult.Status != TransactionResultStatus.Mined)
                {
                    throw new InitializationFailedException("Failed to execute FirstRound.",
                        executionResult.TransactionResult.Error);
                }
            }
            _testDataProvider.SetBlockTime(currentBlockTime.AddMilliseconds(AEDPoSExtensionConstants.MiningInterval)
                .ToTimestamp());
        }

19 View Source File : Round.cs
License : MIT License
Project Creator : AElfProject

public Timestamp GetExpectedEndTime(int missedRoundsCount = 0, int miningInterval = 0)
        {
            if (miningInterval == 0)
            {
                miningInterval = GetMiningInterval();
            }

            var totalMilliseconds = TotalMilliseconds(miningInterval);
            return GetStartTime().AddMilliseconds(totalMilliseconds)
                // Arrange an ending time if this node missed so many rounds.
                .AddMilliseconds(missedRoundsCount * totalMilliseconds)
                .ToTimestamp();
        }

19 View Source File : MinerList.cs
License : MIT License
Project Creator : AElfProject

public Round GenerateFirstRoundOfNewTerm(int miningInterval,
            DateTime currentBlockTime, long currentRoundNumber = 0, long currentTermNumber = 0)
        {
            var sortedMiners =
                (from obj in Pubkeys
                        .ToDictionary<ByteString, string, int>(miner => miner.ToHex(), miner => miner[0])
                    orderby obj.Value descending
                    select obj.Key).ToList();

            var round = new Round();

            for (var i = 0; i < sortedMiners.Count; i++)
            {
                var minerInRound = new MinerInRound();

                // The first miner will be the extra block producer of first round of each term.
                if (i == 0)
                {
                    minerInRound.IsExtraBlockProducer = true;
                }

                minerInRound.Pubkey = sortedMiners[i];
                minerInRound.Order = i + 1;
                minerInRound.ExpectedMiningTime =
                    currentBlockTime.AddMilliseconds((i * miningInterval) + miningInterval).ToTimestamp();
                // Should be careful during validation.
                minerInRound.PreviousInValue = Hash.Empty;

                round.RealTimeMinersInformation.Add(sortedMiners[i], minerInRound);
            }

            round.RoundNumber = currentRoundNumber + 1;
            round.TermNumber = currentTermNumber + 1;
            round.IsMinerListJustChanged = true;

            return round;
        }

19 View Source File : MeetingPatch.cs
License : Apache License 2.0
Project Creator : Aeolic

static void Postfix(ExileController __instance)
        {
            if (IsCultistUsed)
            {
                LastConversion = DateTime.UtcNow.AddMilliseconds(__instance.Duration);
                if (CheckCultistWin())
                {
                    ExecuteCultistWin();
                }
            }
        }

19 View Source File : SnowFlake.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public DateTime GetTime(long timeStamp)
        {
            DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            dtDateTime = dtDateTime.AddMilliseconds(timeStamp).ToLocalTime();
            return dtDateTime;
        }

19 View Source File : LoadBalancingCallInvoker.cs
License : Apache License 2.0
Project Creator : agoda-com

private CallOptions OverrideCallOptions(CallOptions options)
        {
            if (!_timeout.HasValue)
            {
                return options;
            }
            else
            {
                return options.WithDeadline(DateTime.UtcNow.AddMilliseconds(_timeout.Value.TotalMilliseconds));
            }
        }

19 View Source File : MarketDepth.cs
License : Apache License 2.0
Project Creator : AlexWan

public void SetMarketDepthFromString(string str)
        {
            string[] save = str.Split('_');

            int year =
            Convert.ToInt32(save[0][0].ToString() + save[0][1].ToString() + save[0][2].ToString() +
                      save[0][3].ToString());
            int month = Convert.ToInt32(save[0][4].ToString() + save[0][5].ToString());
            int day = Convert.ToInt32(save[0][6].ToString() + save[0][7].ToString());
            int hour = Convert.ToInt32(save[1][0].ToString() + save[1][1].ToString());
            int minute = Convert.ToInt32(save[1][2].ToString() + save[1][3].ToString());
            int second = Convert.ToInt32(save[1][4].ToString() + save[1][5].ToString());

            Time = new DateTime(year, month, day, hour, minute, second);

            Time = Time.AddMilliseconds(Convert.ToInt32(save[2]));

            
            string[] bids = save[3].Split('*');

            Asks = new List<MarketDepthLevel>();

            for (int i = 0; i < bids.Length - 1; i++)
            {
                string[] val = bids[i].Split('&');

                MarketDepthLevel newBid = new MarketDepthLevel();
                newBid.Ask = Convert.ToDecimal(val[0]);
                newBid.Price = Convert.ToDecimal(val[1]);
                Asks.Add(newBid);
            }

            string[] asks = save[4].Split('*');

            Bids = new List<MarketDepthLevel>();

            for (int i = 0; i < asks.Length - 1; i++)
            {
                string[] val = asks[i].Split('&');

                MarketDepthLevel newAsk = new MarketDepthLevel();
                newAsk.Bid = Convert.ToDecimal(val[0]);
                newAsk.Price = Convert.ToDecimal(val[1]);
                Bids.Add(newAsk);
            }
        }

19 View Source File : BinanceServerSpot.cs
License : Apache License 2.0
Project Creator : AlexWan

void _client_NewTradesEvent(TradeResponse trades)
        {
            lock (_newTradesLoker)
            {
                if (trades.data == null)
                {
                    return;
                }
                Trade trade = new Trade();
                trade.SecurityNameCode = trades.data.s;
                trade.Price =
                        trades.data.p.ToDecimal();
                trade.Id = trades.data.t.ToString();
                trade.Time = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(trades.data.T));
                trade.Volume =
                        trades.data.q.ToDecimal();
                trade.Side = trades.data.m == true ? Side.Sell : Side.Buy;

                NewTradesEvent?.Invoke(trade);
            }
        }

19 View Source File : BinanceServerFutures.cs
License : Apache License 2.0
Project Creator : AlexWan

void _client_UpdateMarketDepth(DepthResponseFutures myDepth)
        {
            try
            {
                lock (_depthLocker)
                {
                    if (_depths == null)
                    {
                        _depths = new List<MarketDepth>();
                    }

                    if (myDepth.data.a == null || myDepth.data.a.Count == 0 ||
                        myDepth.data.b == null || myDepth.data.b.Count == 0)
                    {
                        return;
                    }

                    var needDepth = _depths.Find(depth =>
                        depth.SecurityNameCode == myDepth.stream.Split('@')[0].ToUpper());

                    if (needDepth == null)
                    {
                        needDepth = new MarketDepth();
                        needDepth.SecurityNameCode = myDepth.stream.Split('@')[0].ToUpper();
                        _depths.Add(needDepth);
                    }

                    List<MarketDepthLevel> ascs = new List<MarketDepthLevel>();
                    List<MarketDepthLevel> bids = new List<MarketDepthLevel>();

                    for (int i = 0; i < myDepth.data.a.Count; i++)
                    {
                        ascs.Add(new MarketDepthLevel()
                        {
                            Ask =
                                myDepth.data.a[i][1].ToString().ToDecimal()
                            ,
                            Price =
                                myDepth.data.a[i][0].ToString().ToDecimal()

                        });
                    }

                    for (int i = 0; i < myDepth.data.b.Count; i++)
                    {
                        bids.Add(new MarketDepthLevel()
                        {
                            Bid =
                                myDepth.data.b[i][1].ToString().ToDecimal()
                            ,
                            Price =
                                myDepth.data.b[i][0].ToString().ToDecimal()
                        });
                    }

                    needDepth.Asks = ascs;
                    needDepth.Bids = bids;

                    needDepth.Time = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(myDepth.data.T));

                    if (needDepth.Time == DateTime.MinValue)
                    {
                        return;
                    }

                    if (MarketDepthEvent != null)
                    {
                        MarketDepthEvent(needDepth.GetCopy());
                    }
                }
            }
            catch (Exception error)
            {
                SendLogMessage(error.ToString(), LogMessageType.Error);
            }
        }

19 View Source File : BinanceServerFutures.cs
License : Apache License 2.0
Project Creator : AlexWan

void _client_NewTradesEvent(TradeResponse trades)
        {
            lock (_newTradesLoker)
            {
                if (trades.data == null)
                {
                    return;
                }
                Trade trade = new Trade();
                trade.SecurityNameCode = trades.stream.ToString().ToUpper().Split('@')[0];

                if (trade.SecurityNameCode != trades.data.s)
                {
                    return;
                }

                trade.Price =
                        trades.data.p.ToDecimal();
                trade.Id = trades.data.t.ToString();
                trade.Time = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(trades.data.T));
                trade.Volume =
                        trades.data.q.ToDecimal();
                trade.Side = trades.data.m == true ? Side.Sell : Side.Buy;

                NewTradesEvent?.Invoke(trade);            
            }
        }

19 View Source File : TimeManager.cs
License : Apache License 2.0
Project Creator : AlexWan

public static DateTime GetDateTimeFromTimeStamp(long timeStamp)
        {
            return new DateTime(1970, 1, 1).AddMilliseconds(timeStamp);
        }

19 View Source File : LivecoinServer.cs
License : Apache License 2.0
Project Creator : AlexWan

private void Client_NewMarketDepth(OrderBookChannelSubscribedResponse orderBook)
        {
            if (_depths == null)
            {
                _depths = new List<MarketDepth>();
            }

            var newDepth = new MarketDepth();
            newDepth.SecurityNameCode = orderBook.CurrencyPair;

            List<MarketDepthLevel> ascs = new List<MarketDepthLevel>();
            List<MarketDepthLevel> bids = new List<MarketDepthLevel>();

            long biggestTimeStamp = 0;

            foreach (var level in orderBook.Datas)
            {

                if (level.order_type == OrderBookEvent.OrderType.Ask)
                {
                    ascs.Add(new MarketDepthLevel
                    {
                        Price = ParseDecimal(level.Price),
                        Ask = ParseDecimal(level.Quanreplacedy),
                    });
                }
                else
                {
                    bids.Add(new MarketDepthLevel
                    {
                        Price = ParseDecimal(level.Price),
                        Bid = ParseDecimal(level.Quanreplacedy),
                    });
                }

                if (level.Timestamp > biggestTimeStamp)
                {
                    biggestTimeStamp = level.Timestamp;
                }
            }

            newDepth.Asks = ascs;
            newDepth.Bids = bids;

            if (biggestTimeStamp != 0)
            {
                newDepth.Time = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(biggestTimeStamp));
                ServerTime = newDepth.Time;
            }

            _depths.Add(newDepth);

            if (MarketDepthEvent != null)
            {
                MarketDepthEvent(newDepth.GetCopy());
            }


        }

19 View Source File : LivecoinServer.cs
License : Apache License 2.0
Project Creator : AlexWan

private void Client_NewTradesEvent(TradeNotification newTrade)
        {
            foreach (var t in newTrade.Datas)
            {
                OsEngine.Enreplacedy.Trade trade = new OsEngine.Enreplacedy.Trade();
                trade.SecurityNameCode = newTrade.CurrencyPair;

                trade.Id = t.Id.ToString();
                trade.Price =
                   Convert.ToDecimal(
                       t.Price.Replace(".", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator),
                       CultureInfo.InvariantCulture);
                trade.Time = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(t.Timestamp));
                trade.Volume =
                    Convert.ToDecimal(
                        t.Quanreplacedy.Replace(".", CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator),
                        CultureInfo.InvariantCulture);
                trade.Side = t.trade_type == TradeEvent.TradeType.Sell ? Side.Sell : Side.Buy;

                if (NewTradesEvent != null)
                {
                    NewTradesEvent(trade);
                }
            }

        }

19 View Source File : LivecoinServer.cs
License : Apache License 2.0
Project Creator : AlexWan

private void Client_MyOrderEvent(int numUser, string portfolio, PrivateOrderRawEvent orderInfo)
        {
            lock (_orderLocker)
            {
                var needOrder = _myOrders.Find(o => o.NumberUser == numUser);

                if (needOrder == null)
                {
                    return;
                }

                var order = new OsEngine.Enreplacedy.Order();
                order.NumberUser = numUser;
                order.PortfolioNumber = portfolio;
                order.SecurityNameCode = needOrder.SecurityNameCode;

                if (orderInfo.Id == -1)
                {
                    order.State = OrderStateType.Fail;
                    order.Price = needOrder.Price;
                    order.Volume = needOrder.Volume;
                    order.Side = needOrder.Side;
                    order.NumberMarket = needOrder.NumberMarket;

                    MyOrderEvent?.Invoke(order);

                    return;
                }

                order.NumberMarket = orderInfo.Id.ToString();
                order.Price = ParseDecimal(orderInfo.Price);
                order.TimeCallBack = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(orderInfo.Timestamp));
                order.Volume = needOrder.Volume;
                order.Side = orderInfo.order_type == PrivateOrderRawEvent.OrderType.Bid ? Side.Buy : Side.Sell;

                decimal quanreplacedy = ParseDecimal(orderInfo.Quanreplacedy);
                decimal cancelVolume = ParseDecimal(orderInfo.QuanreplacedyLeftBeforeCancellation);

                if (quanreplacedy == 0 && cancelVolume == needOrder.Volume)
                {
                    order.State = OrderStateType.Cancel;
                    DelOrder(needOrder);
                }
                else if (quanreplacedy == 0 && cancelVolume == 0)
                {
                    order.State = OrderStateType.Done;
                    DelOrder(needOrder);
                }
                else if (quanreplacedy == order.Volume)
                {
                    order.State = OrderStateType.Activ;
                }
                else if (needOrder.Volume != quanreplacedy && quanreplacedy != 0)
                {
                    order.State = OrderStateType.Patrial;
                }

                MyOrderEvent?.Invoke(order);
            }
        }

19 View Source File : LivecoinServer.cs
License : Apache License 2.0
Project Creator : AlexWan

private void Client_MyTradeEvent(string orderNumberParent, PrivateTradeEvent tradeInfo)
        {
            MyTrade myTrade = new MyTrade();
            myTrade.NumberTrade = tradeInfo.Id.ToString();
            myTrade.Price = ParseDecimal(tradeInfo.Price);
            myTrade.SecurityNameCode = tradeInfo.CurrencyPair;
            myTrade.Time = new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(tradeInfo.Timestamp));
            myTrade.Side = tradeInfo.trade_type == PrivateTradeEvent.TradeType.Buy ? Side.Buy : Side.Sell;
            myTrade.NumberOrderParent = orderNumberParent;
            myTrade.Volume = ParseDecimal(tradeInfo.Quanreplacedy);

            MyTradeEvent?.Invoke(myTrade);
        }

19 View Source File : LmaxServer.cs
License : Apache License 2.0
Project Creator : AlexWan

private void ClientOnUpdateMarketDepth(OrderBookEvent data)
        {
            try
            {
                lock (_depthLocker)
                {
                    if (_depths == null)
                    {
                        _depths = new List<MarketDepth>();
                    }

                    MarketDepth needDepth = null;

                    var needSecName = _securities.Find(s => s.NameId == data.InstrumentId.ToString()).Name;

                    if (needSecName != null)
                    {
                        needDepth = _depths.Find(depth => depth.SecurityNameCode == needSecName);
                    }

                    if (needDepth == null)
                    {
                        needDepth = new MarketDepth();
                        needDepth.SecurityNameCode = _securities.Find(sec => sec.NameId == data.InstrumentId.ToString()).Name;
                        _depths.Add(needDepth);
                    }

                    needDepth.Asks = new List<MarketDepthLevel>();
                    needDepth.Bids = new List<MarketDepthLevel>();

                    for (int i = 0; data.AskPrices != null && i < data.AskPrices.Count; i++)
                    {
                        needDepth.Asks.Add(new MarketDepthLevel()
                        {
                            Ask = data.AskPrices[i].Quanreplacedy,
                            Price = data.AskPrices[i].Price,
                        });
                    }

                    for (int i = 0; data.BidPrices != null && i < data.BidPrices.Count; i++)
                    {
                        needDepth.Bids.Add(new MarketDepthLevel()
                        {
                            Bid = data.BidPrices[i].Quanreplacedy,
                            Price = data.BidPrices[i].Price,
                        });
                    }

                    needDepth.Time = new DateTime(1970, 1, 1).AddMilliseconds(data.Timestamp);

                    if (needDepth.Time == DateTime.MinValue)
                    {
                        return;
                    }

                    if (MarketDepthEvent != null)
                    {
                        MarketDepthEvent(needDepth.GetCopy());
                    }

                    if (data.LastTradedPrice != Decimal.MinValue)
                    {
                        Trade trade = new Trade();
                        trade.SecurityNameCode = needDepth.SecurityNameCode;
                        trade.Price = data.LastTradedPrice;
                        trade.Time = needDepth.Time;

                        if (NewTradesEvent != null)
                        {
                            NewTradesEvent(trade);
                        }
                    }
                }
            }
            catch (Exception error)
            {
                SendLogMessage(error.ToString(), LogMessageType.Error);
            }
        }

19 View Source File : SnowflakeId.cs
License : MIT License
Project Creator : alonsoalon

public static string replacedyzeId(long Id)
        {
            StringBuilder sb = new StringBuilder();

            var timestamp = (Id >> timestampLeftShift);
            var time = Jan1st1970.AddMilliseconds(timestamp + twepoch);
            sb.Append(time.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss:fff"));

            var datacenterId = (Id ^ (timestamp << timestampLeftShift)) >> datacenterIdShift;
            sb.Append("_" + datacenterId);

            var workerId = (Id ^ ((timestamp << timestampLeftShift) | (datacenterId << datacenterIdShift))) >> workerIdShift;
            sb.Append("_" + workerId);

            var sequence = Id & sequenceMask;
            sb.Append("_" + sequence);

            return sb.ToString();
        }

19 View Source File : OtherExtensions.cs
License : MIT License
Project Creator : aloneguid

public static DateTimeOffset FromUnixMilliseconds(this long unixMilliseconds)
      {
         return UnixEpoch.AddMilliseconds(unixMilliseconds);
      }

19 View Source File : WorkerNodeHostedService.cs
License : MIT License
Project Creator : AlphaYu

public async override Task StopAsync(CancellationToken cancellationToken)
        {
            await base.StopAsync(cancellationToken);

            _logger.LogInformation("stopping service {0}", _serviceName);

            var subtractionMilliseconds = 0 - (_millisecondsDelay * 1.5);
            var score = DateTime.Now.AddMilliseconds(subtractionMilliseconds).GetTotalMilliseconds();
            await _workerNode.RefreshWorkerIdScoreAsync(_serviceName, YitterSnowFlake.CurrentWorkerId, score);

            _logger.LogInformation("stopped service {0}:{1}", _serviceName, score);
        }

19 View Source File : ExtensionMethods.cs
License : MIT License
Project Creator : Altevir

public static DateTime TransformLongToDateTime(this long value)
        {
            return new DateTime(1970, 1, 1).AddMilliseconds(value).ToLocalTime();
        }

19 View Source File : InstanceEventHelperTest.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

[Fact]
        public void RemoveDuplicateEvents_GivenKindOfRealListOfEvents_ReturnsCorrectEvents()
        {
            // Arrange
            DateTime now = DateTime.UtcNow;
            List<InstanceEvent> instanceEvents = new List<InstanceEvent>
            {
                new InstanceEvent // Instance created by user
                {
                    Created = now.AddDays(-6),
                    EventType = InstanceEventType.Created.ToString(),
                    User = new PlatformUser { UserId = 12 }
                },
                new InstanceEvent // Data element created by user, removed
                {
                    Created = now.AddDays(-6).AddMilliseconds(1),
                    EventType = InstanceEventType.Created.ToString(),
                    User = new PlatformUser { UserId = 12 },
                    DataId = "33"
                },
                new InstanceEvent // Data element saved by user, duplicate of next, data id ignored
                {
                    Created = now.AddDays(-6).AddMilliseconds(2),
                    EventType = InstanceEventType.Saved.ToString(),
                    User = new PlatformUser { UserId = 12 },
                    DataId = "33"
                },
                new InstanceEvent // Instance saved by user, duplicate of next, data id ignored
                {
                    Created = now.AddDays(-6).AddMilliseconds(3),
                    EventType = InstanceEventType.Saved.ToString(),
                    User = new PlatformUser { UserId = 12 }
                },
                new InstanceEvent // Data element saved by user, duplicate of next, data id ignored
                {
                    Created = now.AddDays(-5),
                    EventType = InstanceEventType.Saved.ToString(),
                    User = new PlatformUser { UserId = 12 },
                    DataId = "33"
                },
                new InstanceEvent // Data element saved by user, duplicate of next, data id ignored
                {
                    Created = now.AddDays(-5).AddMinutes(3),
                    EventType = InstanceEventType.Saved.ToString(),
                    User = new PlatformUser { UserId = 12 },
                    DataId = "33"
                },
                new InstanceEvent // Instance saved by user, duplicate of next (created removed), data id ignored
                {
                    Created = now.AddDays(-4),
                    EventType = InstanceEventType.Saved.ToString(),
                    User = new PlatformUser { UserId = 12 }
                },
                new InstanceEvent // Data element created by user, removed
                {
                    Created = now.AddDays(-4).AddMilliseconds(1),
                    EventType = InstanceEventType.Created.ToString(),
                    User = new PlatformUser { UserId = 12 },
                    DataId = "35"
                },
                new InstanceEvent // Data element saved by user, duplicate of next
                {
                    Created = now.AddDays(-4).AddMilliseconds(1),
                    EventType = InstanceEventType.Saved.ToString(),
                    User = new PlatformUser { UserId = 12 },
                    DataId = "35"
                },
                new InstanceEvent // Data element saved by user
                {
                    Created = now.AddDays(-4).AddMinutes(12),
                    EventType = InstanceEventType.Saved.ToString(),
                    User = new PlatformUser { UserId = 12 },
                    DataId = "35"
                },
                new InstanceEvent // Data element created by org, removed
                {
                    Created = now.AddDays(-1),
                    EventType = InstanceEventType.Created.ToString(),
                    User = new PlatformUser { OrgId = "ttd" },
                    DataId = "37"
                },
                new InstanceEvent // Data element saved by org
                {
                    Created = now.AddDays(-1).AddMilliseconds(2),
                    EventType = InstanceEventType.Saved.ToString(),
                    User = new PlatformUser { OrgId = "ttd" },
                    DataId = "37"
                },
                new InstanceEvent // Instance saved by user
                {
                    Created = now.AddMilliseconds(-1),
                    EventType = InstanceEventType.Saved.ToString(),
                    User = new PlatformUser { UserId = 12 }
                },
                new InstanceEvent // User submitted 
                {
                    Created = now,
                    EventType = InstanceEventType.Submited.ToString(),
                    User = new PlatformUser { UserId = 12 }
                }
            };

            // Act
            List<InstanceEvent> actual = InstanceEventHelper.RemoveDuplicateEvents(instanceEvents);

            // replacedert
            replacedert.NotNull(actual);
            replacedert.Equal(5, actual.Count);
        }

19 View Source File : MainForm.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko

private void TimeSync()
        {
            double error;
            try
            {
                Log.overlayLog($"时间同步:NTP请求发送");
                var offset = new NtpClient(Settings.Default.NtpServer).GetOffset(out error);
                Log.overlayLog($"时间同步:与北京时间相差{offset.Milliseconds}毫秒");
                //TODO:error handler
                if (CommonUtilities.SetSystemDateTime.SetLocalTimeByStr(
                    DateTime.Now.AddMilliseconds(offset.TotalMilliseconds * -0.5)))
                    tlblTime.Text = "本地时钟已同步";
            }
            catch (Exception e)
            {
                tlblTime.Text = "设置时间出错";
                
            }

           
                
        }

19 View Source File : NtpClient.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko

private DateTime byteToTime(byte[] timeBytes)
        {
            var intPart = ((ulong) timeBytes[0] << 24) | ((ulong) timeBytes[1] << 16) | ((ulong) timeBytes[2] << 8) |
                          timeBytes[3];
            var fractPart = ((ulong) timeBytes[4] << 24) | ((ulong) timeBytes[5] << 16) | ((ulong) timeBytes[6] << 8) |
                            timeBytes[7];

            var milliseconds = intPart * 1000 + fractPart * 1000 / 0x100000000L;
            var networkDateTime = new DateTime(1900, 1, 1).AddMilliseconds((long) milliseconds);
            return networkDateTime;
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : andrew0928

private async void button1_Click(object sender, EventArgs e)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(this.textWebSiteURL.Text);

            HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Head, "/");

            DateTime t0 = DateTime.Now;
            HttpResponseMessage rsp = await client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead);
            DateTime t3 = DateTime.Now;
            TimeSpan duration = t3 - t0;

            if (rsp.Headers.Date.HasValue)
            {
                DateTime t1p = rsp.Headers.Date.Value.LocalDateTime; //DateTime.Parse(rsp.Headers.GetValues("Date").First());
                this.Offset = t1p - t0.AddMilliseconds(duration.TotalMilliseconds / 2);

                this.labelOffset.Text = string.Format(
                    @"時間差: {0} msec, 最大誤差值: {1} msec",
                    this.Offset.TotalMilliseconds,
                    duration.TotalMilliseconds / 2);
            }
            else
            {
                this.labelOffset.Text = @"網站沒有傳回 Date header 資料。";
            }

        }

19 View Source File : LocationExtensions.cs
License : MIT License
Project Creator : anjoy8

internal static DateTimeOffset GetTimestamp(this Android.Locations.Location location)
        {
            try
            {
                return new DateTimeOffset(Epoch.AddMilliseconds(location.Time));
            }
            catch (Exception)
            {
                return new DateTimeOffset(Epoch);
            }
        }

19 View Source File : AbsoluteTimeDateFormatterTest.cs
License : Apache License 2.0
Project Creator : apache

[Test]
        public void CacheWorksForSameSecond()
        {
            StringWriter sw = new StringWriter();
            FormatterOne f1 = new FormatterOne();
            FormatterOne f2 = new FormatterOne();
            DateTime dt1 = DateTime.Today;
            DateTime dt2 = dt1.AddMilliseconds(600);
            f1.FormatDate(dt1, sw);
            f2.FormatDate(dt2, sw);
            replacedert.AreEqual(1, FormatterOne.invocations);
        }

19 View Source File : AbsoluteTimeDateFormatterTest.cs
License : Apache License 2.0
Project Creator : apache

[Test]
        public void CacheExpiresWhenCrossingSecond()
        {
            StringWriter sw = new StringWriter();
            FormatterOne f1 = new FormatterOne();
            FormatterOne f2 = new FormatterOne();
            DateTime dt1 = DateTime.Today.AddMinutes(1);
            DateTime dt2 = dt1.AddMilliseconds(1100);
            f1.FormatDate(dt1, sw);
            f2.FormatDate(dt2, sw);
            replacedert.AreEqual(2, FormatterOne.invocations);
        }

19 View Source File : GridVisualizer.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

private void Update()
        {
            if (Application.isEditor && !Application.isPlaying)
            {
                _nextRefresh = DateTime.UtcNow.AddMilliseconds(this.editorRefreshDelay);
            }
        }

19 View Source File : AppDRESTMetricValue.cs
License : Apache License 2.0
Project Creator : Appdynamics

private static DateTime convertFromUnixTimestamp(long timestamp)
        {
            DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            return origin.AddMilliseconds(timestamp);
        }

19 View Source File : FadeKaraokeType.cs
License : MIT License
Project Creator : arcusmaximus

private static void ApplyFadeOutKaraokeEffect(replacedLine originalLine, replacedLine stepLine, SortedList<TimeSpan, int> activeSectionsPerStep, int stepIdx)
        {
            int stepFirstSectionIdx = 0;
            for (int prevStepIdx = 0; prevStepIdx < stepIdx; prevStepIdx++)
            {
                DateTime fadeStartTime = originalLine.Start + activeSectionsPerStep.Keys[prevStepIdx + 1];
                DateTime fadeEndTime = fadeStartTime.AddMilliseconds(1000);
                int stepLastSectionIdx = activeSectionsPerStep.Values[prevStepIdx] - 1;
                for (int sectionIdx = stepFirstSectionIdx; sectionIdx <= stepLastSectionIdx; sectionIdx++)
                {
                    replacedSection section = (replacedSection)stepLine.Sections[sectionIdx];
                    if (!section.CurrentWordForeColor.IsEmpty && section.CurrentWordForeColor != section.ForeColor)
                        section.Animations.Add(new ForeColorAnimation(fadeStartTime, section.CurrentWordForeColor, fadeEndTime, section.ForeColor, 1));

                    if (!section.CurrentWordShadowColor.IsEmpty)
                    {
                        foreach (KeyValuePair<ShadowType, Color> shadowColor in section.ShadowColors)
                        {
                            if (section.CurrentWordShadowColor != shadowColor.Value)
                                section.Animations.Add(new ShadowColorAnimation(shadowColor.Key, fadeStartTime, section.CurrentWordShadowColor, fadeEndTime, shadowColor.Value, 1));
                        }
                    }

                    if (!section.CurrentWordOutlineColor.IsEmpty && section.CurrentWordOutlineColor != section.ShadowColors.GetOrDefault(ShadowType.Glow))
                        section.Animations.Add(new ShadowColorAnimation(ShadowType.Glow, fadeStartTime, section.CurrentWordOutlineColor, fadeEndTime, section.ShadowColors[ShadowType.Glow], 1));
                }

                stepFirstSectionIdx = stepLastSectionIdx + 1;
            }
        }

19 View Source File : TimeUtil.cs
License : MIT License
Project Creator : arcusmaximus

public static DateTime FrameToStartTime(int frame)
        {
            if (frame <= 0)
                return SubreplacedleDoreplacedent.TimeBase;

            return FrameToTime(frame).AddMilliseconds(-16);
        }

19 View Source File : TimeUtil.cs
License : MIT License
Project Creator : arcusmaximus

public static DateTime FrameToEndTime(int frame)
        {
            return FrameToTime(frame).AddMilliseconds(16);
        }

19 View Source File : WalletTests.cs
License : GNU General Public License v3.0
Project Creator : atomex-me

[Fact]
        public void GetDeterministicSecretTest()
        {
            var mnemonic = new Mnemonic(Wordlist.English, WordCount.TwentyFour);

            var wallet = new HdWallet(mnemonic.ToString(), Wordlist.English, new SecureString(), Network.TestNet);

            var timeStamp = DateTime.UtcNow;

            var secretBtc1 = wallet.GetDeterministicSecret(Common.BtcTestNet, timeStamp);
            var secretBtc2 = wallet.GetDeterministicSecret(Common.BtcTestNet, timeStamp.AddMilliseconds(1));
            replacedert.NotEqual(secretBtc1, secretBtc2);

            var secretBtc3 = wallet.GetDeterministicSecret(Common.BtcTestNet, timeStamp);
            replacedert.Equal(secretBtc1, secretBtc3);

            var secretLtc1 = wallet.GetDeterministicSecret(Common.LtcTestNet, timeStamp);
            replacedert.NotEqual(secretBtc1, secretLtc1);

            var secretXtz1 = wallet.GetDeterministicSecret(Common.XtzTestNet, timeStamp);
            replacedert.NotEqual(secretBtc1, secretXtz1);

            var secretEth1 = wallet.GetDeterministicSecret(Common.EthTestNet, timeStamp);
            replacedert.NotEqual(secretBtc1, secretEth1);
        }

19 View Source File : CachePolicyManager.cs
License : MIT License
Project Creator : Avanade

public static DateTime AddRandomizedOffsetToTime(DateTime time, TimeSpan? offset)
        {
            if (offset.HasValue)
                return time.AddMilliseconds(_random.NextDouble() * offset.Value.TotalMilliseconds);
            else
                return time;
        }

19 View Source File : UniformServerTime.cs
License : Apache License 2.0
Project Creator : awslabs

private DateTime GetBaseNTPServerTime(string ntpserver = "pool.ntp.org")
        {
            var retrycount = 0;
            DateTime servertime = DateTime.MinValue;

            while (retrycount < 3)
            {
                DateTime startTime = DateTime.Now.ToLocalTime();

                try
                {
                    // NTP message size
                    var ntpData = new byte[48];

                    //Setting the Leap Indicator, Version Number and Mode values
                    ntpData[0] = 0x1B; 

                    var addresses = Dns.GetHostEntry(ntpserver).AddressList;

                    //The UDP port number replacedigned to NTP is 123. 
                    var ipEndPoint = new IPEndPoint(addresses[0], 123);

                    var start = Utility.GetElapsedMilliseconds();

                    using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
                    {
                        socket.Connect(ipEndPoint);
                        socket.ReceiveTimeout = 3000;

                        socket.Send(ntpData);
                        socket.Receive(ntpData);
                        socket.Close();
                    }

                    // Calculate the network latency
                    var latency = start - Utility.GetElapsedMilliseconds();

                    //Offset to get to the "Transmit Timestamp" field (time at which the reply 
                    //departed the server for the client, in 64-bit timestamp format."
                    const byte serverReplyTime = 40;

                    //Get the seconds part
                    ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);

                    //Get the seconds fraction
                    ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);

                    intPart = (UInt32)IPAddress.NetworkToHostOrder((int)intPart);
                    fractPart = (UInt32)IPAddress.NetworkToHostOrder((int)fractPart);

                    var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);

                    //**UTC** time
                    var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)((long)milliseconds + (latency / 2)));
                    startTime = networkDateTime;// DateTime.Now;
                    servertime = startTime;

                }
                catch (Exception)
                {
                    servertime = DateTime.MinValue;
                }

                if (servertime == DateTime.MinValue)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                }
                else
                {
                    break;
                }
                retrycount++;
            }

            return servertime;
        }

See More Examples