public override DateTime ReadJson(JsonReader reader, Type objectType, DateTime existingValue, bool hasExistingValue, JsonSerializer serializer) { long utime = (long)reader.Value; return(UnixTimeConverter.FromUnixTime(utime)); }
public static LoginToken GetToken(String emailAddress) { if (!haveReadCacheFile) { ReadCacheFile(); haveReadCacheFile = true; } LoginToken token; if (!Tokens.TryGetValue(emailAddress, out token)) { return(null); } // Ensure the LoginToken is still valid. DateTime expirationTime = token.CreatedAt.ToLocalTime() + UnixTimeConverter.FromUnixTimeSpan(token.ExpiresIn); if (DateTime.Now + ExpirationTimeWindow >= expirationTime) { Tokens.Remove(emailAddress); WriteCacheFile(); token = null; } return(token); }
public Task <LoginToken> GetTokenAsync(string emailAddress) { LoginToken token = null; lock (CacheLock) { if (!_haveReadCacheFile && OSSupportsTokenCache) { ReadCacheFile(); _haveReadCacheFile = true; } if (!Tokens.TryGetValue(emailAddress, out token)) { // Return a task with null return(Task.FromResult <LoginToken>(null)); } // Ensure the LoginToken is still valid. var expirationTime = token.CreatedUtc.ToLocalTime() + UnixTimeConverter.FromUnixTimeSpan(token.ExpiresIn); if (DateTime.Now + ExpirationTimeWindow >= expirationTime) { Tokens.Remove(emailAddress); if (OSSupportsTokenCache) { WriteCacheFile(); } token = null; } } return(Task.FromResult(token)); }
public async Task <IActionResult> Index(DateTime?startDate, DateTime?finishDate) { int startDateUnix = UnixTimeConverter.ConvertToUnixTimestamp(startDate ?? DateTime.Parse("01.01.1970")); int finishDateUnix = UnixTimeConverter.ConvertToUnixTimestamp(finishDate ?? DateTime.Now); ViewBag.StartDate = (startDate ?? DateTime.Parse("01.01.1970")).ToShortDateString(); ViewBag.FinishDate = (finishDate ?? DateTime.Now).ToShortDateString(); List <Groupnom> groupnoms = await _context.Groupnom .Where(b => !b.Deleted) .OrderBy(b => b.Name) .IncludeFilter(b => b.Nomencl .Where(c => !c.Deleted && c.Shipdoc .Any(d => d.Nomenclid == c.Id && d.Shipment.Suppdate >= startDateUnix && d.Shipment.Suppdate <= finishDateUnix))) .ToListAsync(); ViewBag.Supplyer = await _context.Supplyer .Where(b => !b.Deleted) .IncludeFilter(b => b.Shipment.Where(c => !c.Deleted && c.Suppdate >= startDateUnix && c.Suppdate <= finishDateUnix)) .Include(b => b.Shipment) .ThenInclude(c => c.Shipdocs) .ToListAsync(); ViewBag.Shipdocs = await _context.Shipdoc .Include(b => b.Shipment) .Where(b => !b.Shipment.Deleted && startDateUnix <= b.Shipment.Suppdate && finishDateUnix >= b.Shipment.Suppdate) .OrderBy(b => b.Shipment.Suppdate) .ThenBy(c => c.Nomenclid) .ToListAsync(); return(View(groupnoms)); }
public void TestHelper() { //Create /* * * {"Channel":"f1351106ed1b6872d85bbf2eab0e93c9","Comment":"Created by Tv-Browser","Pri":2,"Start":1555594650,"Stop":1555604100,"SubTitle":{"Ger":"(2009)"},"Title":{"Ger":"Die Prinzessin von Montpensier"}} */ Console.WriteLine("Orig:"); Console.WriteLine(UnixTimeConverter.GetDateTimeFromUnixTime(1555587900)); Console.WriteLine(UnixTimeConverter.GetDateTimeFromUnixTime(1555596000)); Console.WriteLine("Auto:"); Console.WriteLine(UnixTimeConverter.GetDateTimeFromUnixTime(1555587450)); Console.WriteLine(UnixTimeConverter.GetDateTimeFromUnixTime(1555596900)); var nowDateTime = DateTime.Now.TrimToSeconds(); var unixTimestamp = UnixTimeConverter.GetUnixTimeFromDateTime(nowDateTime); var csharpDateTime = UnixTimeConverter.GetDateTimeFromUnixTime(unixTimestamp); Console.WriteLine($"{nowDateTime.Ticks} => {csharpDateTime.Ticks}"); Assert.AreEqual(nowDateTime, csharpDateTime); }
public void CovertToUnixDateTime_ReturnsUnixDateTime() { const long expectedUnixDateTime = 1556958281234; DateTime dateTime = new DateTime(2019, 5, 4, 11, 24, 41, 234); long actualUnixDateTime = UnixTimeConverter.CovertToUnixDateTime(dateTime); actualUnixDateTime.Should().Be(expectedUnixDateTime); }
public void CovertFromUnixDateTime_ReturnsDateTime() { const long unixDateTime = 1556958281234; DateTime expectedDateTime = new DateTime(2019, 5, 4, 11, 24, 41, 234); DateTime actualDateTime = UnixTimeConverter.CovertFromUnixDateTime(unixDateTime); actualDateTime.Should().Be(expectedDateTime); }
public void DateTimeToUnixTimestamp_NonDST_ExpectedResult() { var nonDst = new DateTime(2016, 3, 1, 11, 0, 0, DateTimeKind.Utc); const int expected = 1456830000; Assert.AreEqual(UnixTimeConverter.DateTimeToUnixTimestamp(nonDst), expected); Assert.AreEqual(UnixTimeConverter.DateTimeToUnixTimestamp(nonDst.ToLocalTime()), expected); }
public void DateTimeToUnixTimestamp_DST_ExpectedResult() { var dst = new DateTime(2016, 4, 4, 10, 0, 0, DateTimeKind.Utc); const int expected = 1459764000; Assert.AreEqual(UnixTimeConverter.DateTimeToUnixTimestamp(dst), expected); Assert.AreEqual(UnixTimeConverter.DateTimeToUnixTimestamp(dst.ToLocalTime()), expected); }
public void DateTimeToUnixTimestamp_Zero_ExpectedResult() { var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); const int expected = 0; Assert.AreEqual(UnixTimeConverter.DateTimeToUnixTimestamp(epoch), expected); Assert.AreEqual(UnixTimeConverter.DateTimeToUnixTimestamp(epoch.ToLocalTime()), expected); }
public BinanceCandleData(string [] rawData) { OpenTime = UnixTimeConverter.JavaTimeStampToDateTime(Convert.ToInt64(rawData[0])); Open = new decimal(Convert.ToDouble(rawData[1], CultureInfo.InvariantCulture)); High = new decimal(Convert.ToDouble(rawData[2], CultureInfo.InvariantCulture)); Low = new decimal(Convert.ToDouble(rawData[3], CultureInfo.InvariantCulture)); Close = new decimal(Convert.ToDouble(rawData[4], CultureInfo.InvariantCulture)); Volume = new decimal(Convert.ToDouble(rawData[5], CultureInfo.InvariantCulture)); CloseTime = UnixTimeConverter.JavaTimeStampToDateTime(Convert.ToInt64(rawData[6])); }
public void Convert() { var currentDateTime = DateTime.Now; var unixTimeStamp = currentDateTime.ToUnixTime(); var backConvertedUnixTimeStamp = UnixTimeConverter.UnixTimeToDateTime(unixTimeStamp); Assert.AreEqual(currentDateTime.DayOfYear, backConvertedUnixTimeStamp.DayOfYear, 0, "DayOfYear"); Assert.AreEqual(currentDateTime.Hour, backConvertedUnixTimeStamp.Hour, 0, "Hour"); Assert.AreEqual(currentDateTime.Minute, backConvertedUnixTimeStamp.Minute, 0, "Minute"); Assert.AreEqual(currentDateTime.Second, backConvertedUnixTimeStamp.Second, 0, "Second"); }
public async Task <ReadOnlyCollection <WalletBalance> > GetWalletBalancesAsync(CancellationToken cancellationToken = default) { var balancePost = new BitfinexPostBase(); balancePost.Request = BalanceRequestUrl; balancePost.Nonce = UnixTimeConverter.UnixTimeStampUtc().ToString(); var response = await GetRestResponse <ReadOnlyCollection <WalletBalance> >(balancePost, cancellationToken); return(response); }
public async Task <ReadOnlyCollection <Position> > GetActivePositionsAsync(CancellationToken cancellationToken = default) { var activePositionsPost = new BitfinexPostBase { Request = ActivePositionsRequestUrl, Nonce = UnixTimeConverter.UnixTimeStampUtc().ToString() }; var response = await GetRestResponse <ReadOnlyCollection <Position> >(activePositionsPost, cancellationToken); return(response); }
public async Task <object> GetActiveOrders(CancellationToken cancellationToken = default) { var activeOrdersPost = new BitfinexPostBase { Request = ActiveOrdersRequestUrl, Nonce = UnixTimeConverter.UnixTimeStampUtc().ToString() }; var response = await GetRestResponse <IReadOnlyList <Order> >(activeOrdersPost, cancellationToken); return(response); }
public async Task <IEnumerable <int> > GetMissingDates(IEnumerable <IPost> posts, Schedule schedule) { var tempList = posts.ToList(); var missing = new List <int>(); await Task.Run(() => { var firstDate = DateTime.Now; var nextDate = firstDate; int totalCount = tempList.Count(); while (totalCount < MAX_POSTPONED + RESERVE) { var thisDayDate = nextDate; var thisDayPosts = tempList.Where(i => UnixTimeConverter.ToDateTime(i.Date).Date == thisDayDate.Date).ToList(); foreach (var scheduleItem in schedule.Items) { if (totalCount >= MAX_POSTPONED + RESERVE) { break; } var scheduledDate = ConvertScheduleItemToDateTime(new DateTime(thisDayDate.Year, thisDayDate.Month, thisDayDate.Day), scheduleItem); if (scheduledDate <= DateTime.Now) { continue; } var isTimeCorrectlyScheduled = thisDayPosts.Any(i => IsTimeCorrectlyScheduled(i.Date, scheduleItem)); if (isTimeCorrectlyScheduled == false) { totalCount++; missing.Add(UnixTimeConverter.ToUnix(scheduledDate)); } } nextDate = nextDate.AddDays(1); } missing.Sort((a, b) => a.CompareTo(b)); return(missing); }); return(missing); }
public async Task <ReadOnlyCollection <MarginInfo> > GetMarginInformationAsync(CancellationToken cancellationToken = default) { var marginPost = new BitfinexPostBase { Request = MarginInfoRequstUrl, Nonce = UnixTimeConverter.UnixTimeStampUtc().ToString() }; var response = await GetRestResponse <ReadOnlyCollection <MarginInfo> >(marginPost, cancellationToken); return(response); }
public async Task <Order> GetOrderStatusAsync(long orderId, CancellationToken cancellationToken = default) { var orderStatusPost = new BitfinexOrderStatusPost { Request = OrderStatusRequestUrl, Nonce = UnixTimeConverter.UnixTimeStampUtc().ToString(), OrderId = orderId }; var response = await GetRestResponse <Order>(orderStatusPost, cancellationToken); return(response); }
/// <summary> /// Reads and parses <see cref="Signon"/>s from the <c>signons.sqlite</c> database. /// </summary> /// <param name="path">The absolute path to the <c>signons.sqlite</c> file.</param> /// <returns>The parsed <see cref="Signon"/>s.</returns> internal static IEnumerable <Signon> ParseDatabase(string path) { var connectionBuilder = new SQLiteConnectionStringBuilder { DataSource = path, Version = 3, FailIfMissing = true, ReadOnly = true }; const string CommandText = @"SELECT hostname, httpRealm, formSubmitURL, usernameField, passwordField, encryptedUsername, encryptedPassword, timeCreated, timeLastUsed, timePasswordChanged, timesUsed FROM moz_logins ORDER BY hostname"; // Doesn't handle exceptions since they were just being rethrown anyway. Default messages are adequately descriptive. using (var connection = new SQLiteConnection(connectionBuilder.ConnectionString).OpenAndReturn()) using (var command = new SQLiteCommand(CommandText, connection)) using (SQLiteDataReader reader = command.ExecuteReader()) { while (reader.Read()) { yield return(new Signon { Hostname = reader.GetString("hostname"), HttpRealm = reader.GetString("httpRealm"), Username = NssUtils.DecodeAndDecrypt(reader.GetString("encryptedUsername")), UserNameField = reader.GetString("usernameField"), Password = NssUtils.DecodeAndDecrypt(reader.GetString("encryptedPassword")), PasswordField = reader.GetString("passwordField"), FormSubmitUrl = reader.GetString("formSubmitURL"), TimeCreated = UnixTimeConverter.Convert(reader.GetNullableUInt64("timeCreated")), TimeLastUsed = UnixTimeConverter.Convert(reader.GetNullableUInt64("timeLastUsed")), TimePasswordChanged = UnixTimeConverter.Convert(reader.GetNullableUInt64("timePasswordChanged")), TimesUsed = reader.GetUInt64("timesUsed") }); } } }
public async Task <IActionResult> Create([Bind("Supplyerid")] Shipment shipment) { if (ModelState.IsValid) { shipment.Suppdate = UnixTimeConverter.ConvertToUnixTimestamp(DateTime.Now.Date); shipment.Deleted = false; _context.Add(shipment); await _context.SaveChangesAsync(); return(RedirectToAction("Create", "Shipdocs", new { shipmentid = shipment.Id })); } ViewData["Supplyerid"] = new SelectList(_context.Supplyer.Where(b => !b.Deleted), "Id", "Name", shipment.Supplyerid); return(View(shipment)); }
public async Task <Order> AddOrderAsync(NewOrderRequest orderRequest, CancellationToken cancellationToken = default) { var newOrder = new BitfinexNewOrderPost { Symbol = orderRequest.Symbol, Amount = orderRequest.Аmount, Price = orderRequest.Price, Exchange = Exchange, Side = orderRequest.Side, Type = orderRequest.Type, Request = NewOrderRequestUrl, Nonce = UnixTimeConverter.UnixTimeStampUtc().ToString() }; var response = await GetRestResponse <Order>(newOrder, cancellationToken); return(response); }
public async Task <object> AddOrder(string symbol, decimal amount, decimal price, string side, string type, CancellationToken cancellationToken = default) { var newOrder = new BitfinexNewOrderPost { Symbol = symbol, Amount = amount, Price = price, Exchange = Exchange, Side = side, Type = type, Request = NewOrderRequestUrl, Nonce = UnixTimeConverter.UnixTimeStampUtc().ToString() }; var response = await GetRestResponse <Order>(newOrder, cancellationToken); return(response); }
public static TradeExecutionUpdate Parse(string json) { if (JToken.Parse(json).Type != JTokenType.Array) { return(null); } var arr = JArray.Parse(json); if (!(arr[0].Type == JTokenType.Integer && arr[1].Type == JTokenType.String && arr[2].Type == JTokenType.Array)) { return(null); } if (arr[1].Value <string>() != @"tu") { return(null); } var item = arr[2].Value <JArray>(); return(new TradeExecutionUpdate { ChannelId = arr[0].Value <long>(), Seq = item[0].Value <string>(), Id = item[1].Value <long>(), AssetPair = item[2].Value <string>(), TimeStamp = UnixTimeConverter.FromUnixTime(item[3].Value <long>()), OrderId = item[4].Value <long>(), Volume = item[5].Value <decimal>(), Price = item[6].Value <decimal>(), OrderType = item[7].Value <string>(), OrderPrice = item[8].Value <decimal?>(), Fee = item[9].Value <decimal>(), FeeCurrency = item[10].Value <string>() }); }
public IEnumerable <ProductInShelf> GetProductsInShelf(Shelf shelf) { string rawJson = webClient.DownloadString(String.Format("/azusa/products/inshelf/{0}", shelf.Id)); JArray deserializeObject = (JArray)JsonConvert.DeserializeObject(rawJson); foreach (JToken jToken in deserializeObject) { ProductInShelf productInShelf = new ProductInShelf(); productInShelf.CoverSize = jToken.Value <long>("CoverSize"); productInShelf.BoughtOn = UnixTimeConverter.FromUnixTime(jToken.Value <long>("BoughtOn")); productInShelf.ContainsUndumped = jToken.Value <bool>("ContainsUndumped"); productInShelf.IconId = jToken.Value <int>("IconId"); productInShelf.Id = jToken.Value <int>("Id"); productInShelf.MissingGraphData = jToken.Value <int>("MissingGraphData"); productInShelf.NSFW = jToken.Value <bool>("NSFW"); productInShelf.Name = jToken.Value <string>("Name"); productInShelf.NumberOfDiscs = jToken.Value <int>("NumberOfDiscs"); productInShelf.Price = jToken.Value <double>("Price"); productInShelf.relatedShelf = shelf; yield return(productInShelf); } yield break; }
protected override QueryStringParametersList GetQueryStringParameters() { if (Location == null) { throw new ArgumentException("Location is required"); } if (TimeStamp == null) { throw new ArgumentException("TimeStamp is required"); } var parameters = base.GetQueryStringParameters(); parameters.Add("location", this.Location.LocationString); parameters.Add("timestamp", UnixTimeConverter.DateTimeToUnixTimestamp(this.TimeStamp).ToString()); if (!string.IsNullOrWhiteSpace(Language)) { parameters.Add("language", Language); } return(parameters); }
public static SearchQuery GetSearchQuery(Folder folder) { bool exists = false; AzusaContext context = AzusaContext.GetInstance(); int count = context.DatabaseDriver.MailArchive_CountItemsInFolder(folder); exists = count > 0; if (!exists) { return(SearchQuery.All); } long newestUtime = context.DatabaseDriver.MailArchive_GetHighestMessageUTimeInFolder(folder); if (newestUtime > 0) { return(SearchQuery.DeliveredAfter(UnixTimeConverter.FromUnixTime(newestUtime))); } else { return(SearchQuery.All); } }
/// <summary> /// Selects daily weather forecast for location's estimated date. /// </summary> /// <param name="location">Location</param> /// <param name="forecast">Forecasts for location</param> /// <returns>Forecast for the day</returns> public ForecastDailyEntry SelectLongTermEntry(LocationDetail location, ForecastLongTerm forecast) { if (location == null) { throw new ArgumentNullException("Location is null"); } if (forecast == null) { throw new ArgumentNullException("Forecast is null"); } var entry = forecast.Entries.FirstOrDefault(x => x.ForecastTime.Date == location.Time.Date); if (entry == null) { string msg = "No forecast for the day selected"; log.Error(msg); int hrs = 12; int min = 0; var lastEntry = forecast.Entries.LastOrDefault(); if (lastEntry != null) { hrs = lastEntry.ForecastTime.Hour; min = lastEntry.ForecastTime.Minute; } return(new ForecastDailyEntry() { Clouds = 0, Deg = 0, Humidity = 0, Pressure = 0, Rain = 0, Speed = 0, Temp = new Temp() { Day = 0, Eve = 0, Max = 0, Min = 0, Morn = 0, Night = 0 }, UnixTimestamp = (int)UnixTimeConverter.DateTimeToUnixTimestamp( new DateTime() .AddYears(location.Time.Year) .AddMonths(location.Time.Month) .AddDays(location.Time.Day) .AddHours(hrs) .AddMinutes(min)), WeatherDescription = new List <WeatherDescription>() { new WeatherDescription() { Description = "N/A", Icon = "N/A", Id = 0, Main = "N/A" } } }); //throw new NullReferenceException(msg); } return(entry); }
//todo: put this somewhere else public bool IsDateMatchTheSchedule(int unixTime, Schedule schedule) { var dateTime = UnixTimeConverter.ToDateTime(unixTime); return(schedule.Items.Any(i => i.Hour == dateTime.Hour && i.Minute == dateTime.Minute)); }
protected override QueryStringParametersList GetQueryStringParameters() { if (string.IsNullOrWhiteSpace(Origin)) { throw new ArgumentException("Must specify an Origin"); } if (string.IsNullOrWhiteSpace(Destination)) { throw new ArgumentException("Must specify a Destination"); } if (!Enum.IsDefined(typeof(AvoidWay), Avoid)) { throw new ArgumentException("Invalid enumeration value for 'Avoid'"); } if (!Enum.IsDefined(typeof(TravelMode), TravelMode)) { throw new ArgumentException("Invalid enumeration value for 'TravelMode'"); } if (TravelMode == TravelMode.Transit && (DepartureTime == default(DateTime) && ArrivalTime == default(DateTime))) { throw new ArgumentException("You must set either DepatureTime or ArrivalTime when TravelMode = Transit"); } var parameters = base.GetQueryStringParameters(); parameters.Add("origin", Origin); parameters.Add("destination", Destination); parameters.Add("mode", TravelMode.ToString().ToLower()); if (Alternatives) { parameters.Add("alternatives", "true"); } if (Avoid != AvoidWay.Nothing) { parameters.Add("avoid", Avoid.ToString().ToLower()); } if (!string.IsNullOrWhiteSpace(Language)) { parameters.Add("language", Language); } if (Waypoints != null && Waypoints.Any()) { IEnumerable <string> waypoints; if (OptimizeWaypoints) { const string optimizeWaypoints = "optimize:true"; waypoints = new string[] { optimizeWaypoints }.Concat(Waypoints); } else { waypoints = Waypoints; } parameters.Add("waypoints", string.Join("|", waypoints)); } if (ArrivalTime != default(DateTime)) { parameters.Add("arrival_time", UnixTimeConverter.DateTimeToUnixTimestamp(ArrivalTime).ToString(CultureInfo.InvariantCulture)); } if (DepartureTime != default(DateTime)) { parameters.Add("departure_time", UnixTimeConverter.DateTimeToUnixTimestamp(DepartureTime).ToString(CultureInfo.InvariantCulture)); } return(parameters); }
public long Time() { return(UnixTimeConverter.CurrentUnixTimeMillis()); }