System.DateTime.ToLocalTime()

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

683 Examples 7

19 Source : ZipEntry.cs
with MIT License
from ay2015

internal void ProcessExtraData(bool localHeader)
		{
			ZipExtraData extraData = new ZipExtraData(this.extra);

			if ( extraData.Find(0x0001) ) {
                // Version required to extract is ignored here as some archivers dont set it correctly
                // in theory it should be version 45 or higher

				// The recorded size will change but remember that this is zip64.
				forceZip64_ = true;

				if ( extraData.ValueLength < 4 ) {
					throw new ZipException("Extra data extended Zip64 information length is invalid");
				}

				if ( localHeader || (size == uint.MaxValue) ) {
					size = (ulong)extraData.ReadLong();
				}

				if ( localHeader || (compressedSize == uint.MaxValue) ) {
					compressedSize = (ulong)extraData.ReadLong();
				}

				if ( !localHeader && (offset == uint.MaxValue) ) {
					offset = extraData.ReadLong();
				}

                // Disk number on which file starts is ignored
			}
			else {
				if ( 
					((versionToExtract & 0xff) >= ZipConstants.VersionZip64) &&
					((size == uint.MaxValue) || (compressedSize == uint.MaxValue))
				) {
					throw new ZipException("Zip64 Extended information required but is missing.");
				}
			}

			if ( extraData.Find(10) ) {
				// No room for any tags.
				if ( extraData.ValueLength < 4 ) {
					throw new ZipException("NTFS Extra data invalid");
				}

				extraData.ReadInt(); // Reserved

				while ( extraData.UnreadCount >= 4 ) {
					int ntfsTag = extraData.ReadShort();
					int ntfsLength = extraData.ReadShort();
					if ( ntfsTag == 1 ) {
						if ( ntfsLength >= 24 ) {
							long lastModification = extraData.ReadLong();
							long lastAccess = extraData.ReadLong();
							long createTime = extraData.ReadLong();

							DateTime = System.DateTime.FromFileTime(lastModification);
						}
						break;
					}
					else {
						// An unknown NTFS tag so simply skip it.
						extraData.Skip(ntfsLength);
					}
				}
			}
			else if ( extraData.Find(0x5455) ) {
				int length = extraData.ValueLength;	
				int flags = extraData.ReadByte();
					
				// Can include other times but these are ignored.  Length of data should
				// actually be 1 + 4 * no of bits in flags.
				if ( ((flags & 1) != 0) && (length >= 5) ) {
					int iTime = extraData.ReadInt();

					DateTime = (new System.DateTime ( 1970, 1, 1, 0, 0, 0 ).ToUniversalTime() +
						new TimeSpan ( 0, 0, 0, iTime, 0 )).ToLocalTime();
				}
			}
			if (method == CompressionMethod.WinZipAES) {
				ProcessAESExtraData(extraData);
			}
		}

19 Source : DefaultTimeSource.cs
with MIT License
from azist

public DateTime UniversalTimeToLocalizedTime(DateTime utc)
    {
        if (utc.Kind!=DateTimeKind.Utc)
          throw new TimeException(StringConsts.ARGUMENT_ERROR+GetType().Name+".UniversalTimeToLocalizedTime(utc.Kind!=UTC)");

        var loc = TimeLocation;
        if (!loc.UseParentSetting)
        {
            return DateTime.SpecifyKind(utc + loc.UTCOffset, DateTimeKind.Local);
        }
        else
        {
            return utc.ToLocalTime();
        }
    }

19 Source : TimeScalePane.cs
with MIT License
from azist

protected virtual string OnTimeLineFormat(DateTime time, Tick priorTick, bool isCursor)
    {
      if (TimeLineFormat != null)
        return TimeLineFormat(this, new TimeLineFormatEventArgs(time, priorTick, isCursor));

      var tm = Chart.UseLocalTime ? time.ToLocalTime() : time;

      if (isCursor || priorTick == null || priorTick.Sample.TimeStamp.Day != time.Day)
        return "{0}-{1:D2}-{2:D2}{3}{4:D2}:{5:D2}:{6:D2}".Args
               (tm.Year, tm.Month, tm.Day, AllowMultiLinereplacedle ? "\n" : " ", tm.Hour, tm.Minute, tm.Second);
      if (priorTick.Sample.TimeStamp.Hour != time.Hour)
        return "{0:D2}:{1:D2}:{2:D2}".Args(tm.Hour, tm.Minute, tm.Second);

      return "{0:D2}:{1:D2}".Args(tm.Minute, tm.Second);
    }

19 Source : Schedule.cs
with Apache License 2.0
from Azure-App-Service

public TimeSpan GetNextInterval(DateTime lastSchedule, bool ignoreMissed = false)
        {
            DateTime now = _dateTimeNowProvider.Now;

            lastSchedule = lastSchedule == DateTime.MinValue ? now : lastSchedule.ToLocalTime();

            // Check for next occurence from last occurence
            DateTime nextOccurrence = _crontabSchedule.GetNextOccurrence(lastSchedule);

            // Note: For calculations, we use DateTimeOffsets and TimeZoneInfo to ensure we honor time zone
            // changes (e.g. Daylight Savings Time)
            var nowOffset = new DateTimeOffset(now, TimeZoneInfo.Local.GetUtcOffset(now));
            var nextOffset = new DateTimeOffset(nextOccurrence, TimeZoneInfo.Local.GetUtcOffset(nextOccurrence));
            if (nextOffset >= nowOffset)
            {
                // If next occurence is in the future use it
                return nextOffset - nowOffset;
            }

            // Otherwise if next occurence is up to 10 minutes in the past or ignore missed is true use now
            if (ignoreMissed || nextOccurrence >= now - TimeSpan.FromMinutes(10))
            {
                return TimeSpan.Zero;
            }

            var nextOccurrences = _crontabSchedule.GetNextOccurrences(lastSchedule, now);
            int nextOccurrencesCount = nextOccurrences.Count();
            if (nextOccurrencesCount > 0)
            {
                _logger.LogWarning("Missed {0} schedules, most recent at {1}".FormatCurrentCulture(nextOccurrencesCount, nextOccurrences.Last()));
            }

            // Return next occurence after now
            nextOccurrence = _crontabSchedule.GetNextOccurrence(now);
            nextOffset = new DateTimeOffset(nextOccurrence, TimeZoneInfo.Local.GetUtcOffset(nextOccurrence));
            return nextOffset - nowOffset;
        }

19 Source : DateTimeExt.cs
with MIT License
from baba-s

public static DateTime FromUnixTime( this DateTime self, long unixTime )
		{
			return UNIX_EPOCH.AddSeconds( unixTime ).ToLocalTime();
		}

19 Source : LogData.cs
with MIT License
from baaron4

private string GetDateTime(double unixSeconds)
        {
            var dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            dtDateTime = dtDateTime.AddSeconds(unixSeconds).ToLocalTime();
            return dtDateTime.ToString(_dateFormat);
        }

19 Source : LogData.cs
with MIT License
from baaron4

private string GetDateTimeStd(double unixSeconds)
        {
            var dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            dtDateTime = dtDateTime.AddSeconds(unixSeconds).ToLocalTime();
            return dtDateTime.ToString(_dateFormatStd);
        }

19 Source : Extensions.cs
with GNU General Public License v3.0
from BardMusicPlayer

public static DateTime ToLocalDateTime(this long timestamp) => new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(timestamp).ToLocalTime();

19 Source : ChatEntry.cs
with GNU General Public License v3.0
from BardMusicPlayer

public static DateTime UnixTimeStampToDateTime(double unixTimeStamp) {
            var dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();
            return dtDateTime;
        }

19 Source : TimeManager.cs
with MIT License
from Battlerax

public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
        {
            // Unix timestamp is seconds past epoch
            System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
            dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();
            return dtDateTime;
        }

19 Source : ExampleSavePosition.cs
with MIT License
from BayatGames

void Start()
        {
            _encodePreplacedword = "12345678910abcdef12345678910abcdef";
            SaveGame.EncodePreplacedword = _encodePreplacedword;
            SaveGame.Encode = true;
            SaveGame.Serializer = new SaveGameFree.Serializers.SaveGameBinarySerializer();
            StorageSG ssg = new StorageSG();
            SaveGame.Save<StorageSG>("pizza2", ssg);
            StorageSG ssgLoaded = SaveGame.Load<StorageSG>("pizza2");
            Debug.Log(ssgLoaded.myDateTime.ToLocalTime().ToString());
            if (loadOnStart)
            {
                Load();
            }
        }

19 Source : MeasurementTools.cs
with MIT License
from bitbeans

private static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
	    {
		    var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
		    dateTime = dateTime.AddSeconds(unixTimeStamp).ToLocalTime();
		    return dateTime;
	    }

19 Source : Util.cs
with MIT License
from bitrinjani

public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
        {
            var dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();
            return dtDateTime;
        }

19 Source : ExportExtendedAttributesQuery.cs
with MIT License
from blazorhero

public async Task<Result<string>> Handle(ExportExtendedAttributesQuery<TId, TEnreplacedyId, TEnreplacedy, TExtendedAttribute> request, CancellationToken cancellationToken)
        {
            var extendedAttributeFilterSpec = new ExtendedAttributeFilterSpecification<TId, TEnreplacedyId, TEnreplacedy, TExtendedAttribute>(request);
            var extendedAttributes = await _unitOfWork.Repository<TExtendedAttribute>().Enreplacedies
                .Specify(extendedAttributeFilterSpec)
                .ToListAsync(cancellationToken);

            // check SearchString outside of specification because of
            // an expression tree lambda may not contain a null propagating operator
            if (!string.IsNullOrWhiteSpace(request.SearchString))
            {
                extendedAttributes = extendedAttributes.Where(p =>
                        p.Key.Contains(request.SearchString, StringComparison.InvariantCultureIgnoreCase)
                        || p.Decimal?.ToString().Contains(request.SearchString, StringComparison.InvariantCultureIgnoreCase) == true
                        || p.Text?.Contains(request.SearchString, StringComparison.InvariantCultureIgnoreCase) == true
                        || p.DateTime?.ToString("G", CultureInfo.CurrentCulture).Contains(request.SearchString, StringComparison.InvariantCultureIgnoreCase) == true
                        || p.Json?.Contains(request.SearchString, StringComparison.InvariantCultureIgnoreCase) == true
                        || p.ExternalId?.Contains(request.SearchString, StringComparison.InvariantCultureIgnoreCase) == true
                        || p.Description?.Contains(request.SearchString, StringComparison.InvariantCultureIgnoreCase) == true
                        || p.Group?.Contains(request.SearchString, StringComparison.InvariantCultureIgnoreCase) == true)
                    .ToList();
            }

            var mappers = new Dictionary<string, Func<TExtendedAttribute, object>>
            {
                {_localizer["Id"], item => item.Id},
                {_localizer["EnreplacedyId"], item => item.EnreplacedyId},
                {_localizer["Type"], item => item.Type},
                {_localizer["Key"], item => item.Key},
                {
                    _localizer["Value"], item => item.Type switch
                    {
                        EnreplacedyExtendedAttributeType.Decimal => item.Decimal,
                        EnreplacedyExtendedAttributeType.Text => item.Text,
                        EnreplacedyExtendedAttributeType.DateTime => item.DateTime != null ? DateTime.SpecifyKind((DateTime)item.DateTime, DateTimeKind.Utc).ToLocalTime().ToString("G", CultureInfo.CurrentCulture) : string.Empty,
                        EnreplacedyExtendedAttributeType.Json => item.Json,
                        _ => throw new ArgumentOutOfRangeException(nameof(item.Type), _localizer["Type should be valid"])
                    }

19 Source : AuditTrails.razor.cs
with MIT License
from blazorhero

private async Task GetDataAsync()
        {
            var response = await AuditManager.GetCurrentUserTrailsAsync();
            if (response.Succeeded)
            {
                Trails = response.Data
                    .Select(x => new RelatedAuditTrail
                    {
                        AffectedColumns = x.AffectedColumns,
                        DateTime = x.DateTime,
                        Id = x.Id,
                        NewValues = x.NewValues,
                        OldValues = x.OldValues,
                        PrimaryKey = x.PrimaryKey,
                        TableName = x.TableName,
                        Type = x.Type,
                        UserId = x.UserId,
                        LocalTime = DateTime.SpecifyKind(x.DateTime, DateTimeKind.Utc).ToLocalTime()
                    }).ToList();
            }
            else
            {
                foreach (var message in response.Messages)
                {
                    _snackBar.Add(message, Severity.Error);
                }
            }
        }

19 Source : UserService.cs
with MIT License
from blazorhero

public async Task<string> ExportToExcelAsync(string searchString = "")
        {
            var userSpec = new UserFilterSpecification(searchString);
            var users = await _userManager.Users
                .Specify(userSpec)
                .OrderByDescending(a => a.CreatedOn)
                .ToListAsync();
            var result = await _excelService.ExportAsync(users, sheetName: _localizer["Users"],
                mappers: new Dictionary<string, Func<BlazorHeroUser, object>>
                {
                    { _localizer["Id"], item => item.Id },
                    { _localizer["FirstName"], item => item.FirstName },
                    { _localizer["LastName"], item => item.LastName },
                    { _localizer["UserName"], item => item.UserName },
                    { _localizer["Email"], item => item.Email },
                    { _localizer["EmailConfirmed"], item => item.EmailConfirmed },
                    { _localizer["PhoneNumber"], item => item.PhoneNumber },
                    { _localizer["PhoneNumberConfirmed"], item => item.PhoneNumberConfirmed },
                    { _localizer["IsActive"], item => item.IsActive },
                    { _localizer["CreatedOn (Local)"], item => DateTime.SpecifyKind(item.CreatedOn, DateTimeKind.Utc).ToLocalTime().ToString("G", CultureInfo.CurrentCulture) },
                    { _localizer["CreatedOn (UTC)"], item => item.CreatedOn.ToString("G", CultureInfo.CurrentCulture) },
                    { _localizer["ProfilePictureDataUrl"], item => item.ProfilePictureDataUrl },
                });

            return result;
        }

19 Source : AuditService.cs
with MIT License
from blazorhero

public async Task<IResult<string>> ExportToExcelAsync(string userId, string searchString = "", bool searchInOldValues = false, bool searchInNewValues = false)
        {
            var auditSpec = new AuditFilterSpecification(userId, searchString, searchInOldValues, searchInNewValues);
            var trails = await _context.AuditTrails
                .Specify(auditSpec)
                .OrderByDescending(a => a.DateTime)
                .ToListAsync();
            var data = await _excelService.ExportAsync(trails, sheetName: _localizer["Audit trails"],
                mappers: new Dictionary<string, Func<Audit, object>>
                {
                    { _localizer["Table Name"], item => item.TableName },
                    { _localizer["Type"], item => item.Type },
                    { _localizer["Date Time (Local)"], item => DateTime.SpecifyKind(item.DateTime, DateTimeKind.Utc).ToLocalTime().ToString("G", CultureInfo.CurrentCulture) },
                    { _localizer["Date Time (UTC)"], item => item.DateTime.ToString("G", CultureInfo.CurrentCulture) },
                    { _localizer["Primary Key"], item => item.PrimaryKey },
                    { _localizer["Old Values"], item => item.OldValues },
                    { _localizer["New Values"], item => item.NewValues },
                });

            return await Result<string>.SuccessAsync(data: data);
        }

19 Source : DateTimeExtensions.cs
with GNU Affero General Public License v3.0
from blockbasenetwork

public static DateTime UnixTimeStampToDateTime(long unixTimeStamp)
        {
            // Unix timestamp is seconds past epoch
            System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
            dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();
            return dtDateTime;
        }

19 Source : Utilities.cs
with MIT License
from blockcoli

public static DateTime UnixTimeStampToDateTime(this ulong unixTimeStamp)
        {
            try
            {
                // TODO
                //1562008648525
                var dtDateTime = DateTimeOffset.FromUnixTimeSeconds((long)unixTimeStamp)
                                       .DateTime.ToLocalTime();
                return dtDateTime;
            }
            catch
            {
                return DateTime.MinValue;
            }
        }

19 Source : RelativeTime.cs
with MIT License
from bolorundurowb

public static string CalendarTime(this DateTime This, DateTime dateTime,
            CalendarTimeFormats formats = null)
        {
            formats = formats ?? new CalendarTimeFormats();
            var startDate = This.Kind == DateTimeKind.Local ? This : This.ToLocalTime();
            var endDate = dateTime.Kind == DateTimeKind.Local ? dateTime : dateTime.ToLocalTime();
            var timeDiff = endDate - startDate;

            if (startDate.Date == endDate.Date)
            {
                return endDate.ToString(formats.SameDay);
            }

            if (startDate.AddDays(1).Date == endDate.Date)
            {
                return endDate.ToString(formats.NextDay);
            }

            if (startDate.AddDays(-1).Date == endDate.Date)
            {
                return endDate.ToString(formats.LastDay);
            }

            if (timeDiff.TotalDays > 1 && timeDiff.TotalDays < 7)
            {
                return endDate.ToString(formats.NextWeek);
            }

            if (timeDiff.TotalDays >= -6 && timeDiff.TotalDays < -1)
            {
                return endDate.ToString(formats.LastWeek);
            }

            return endDate.ToString(formats.EverythingElse);
        }

19 Source : JSON.cs
with GNU General Public License v3.0
from bonarr

private DateTime CreateDateTime(string value)
        {
            bool utc = false;
            //                   0123456789012345678
            // datetime format = yyyy-MM-dd HH:mm:ss
            int year = (int)CreateLong(value.Substring(0, 4));
            int month = (int)CreateLong(value.Substring(5, 2));
            int day = (int)CreateLong(value.Substring(8, 2));
            int hour = (int)CreateLong(value.Substring(11, 2));
            int min = (int)CreateLong(value.Substring(14, 2));
            int sec = (int)CreateLong(value.Substring(17, 2));

            if (value.EndsWith("Z"))
                utc = true;

            if (UseUTCDateTime == false && utc == false)
                return new DateTime(year, month, day, hour, min, sec);
            return new DateTime(year, month, day, hour, min, sec, DateTimeKind.Utc).ToLocalTime();
        }

19 Source : TinyTwitter.cs
with GNU General Public License v3.0
from bonarr

private IEnumerable<Tweet> GetTimeline(string url, long? sinceId, long? maxId, int? count, string screenName)
        {
            var builder = new RequestBuilder(oauth, "GET", url);

            if (sinceId.HasValue)
                builder.AddParameter("since_id", sinceId.Value.ToString());

            if (maxId.HasValue)
                builder.AddParameter("max_id", maxId.Value.ToString());

            if (count.HasValue)
                builder.AddParameter("count", count.Value.ToString());

            if (screenName != "")
                builder.AddParameter("screen_name", screenName);

            var responseContent = builder.Execute();

            var serializer = new JavaScriptSerializer();

            var tweets = (object[])serializer.DeserializeObject(responseContent);

            return tweets.Cast<Dictionary<string, object>>().Select(tweet =>
            {
                var user = ((Dictionary<string, object>)tweet["user"]);
                var date = DateTime.ParseExact(tweet["created_at"].ToString(),
                    "ddd MMM dd HH:mm:ss zz00 yyyy",
                    CultureInfo.InvariantCulture).ToLocalTime();

                return new Tweet
                {
                    Id = (long)tweet["id"],
                    CreatedAt = date,
                    Text = (string)tweet["text"],
                    UserName = (string)user["name"],
                    ScreenName = (string)user["screen_name"]
                };
            }).ToArray();
        }

19 Source : CookieCollection.cs
with MIT License
from bonzaiferroni

private static CookieCollection parseResponse (string value)
    {
      var cookies = new CookieCollection ();

      Cookie cookie = null;
      var pairs = splitCookieHeaderValue (value);
      for (int i = 0; i < pairs.Length; i++) {
        var pair = pairs [i].Trim ();
        if (pair.Length == 0)
          continue;

        if (pair.StartsWith ("version", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Version = Int32.Parse (pair.GetValueInternal ("=").Trim ('"'));
        }
        else if (pair.StartsWith ("expires", StringComparison.InvariantCultureIgnoreCase)) {
          var buffer = new StringBuilder (pair.GetValueInternal ("="), 32);
          if (i < pairs.Length - 1)
            buffer.AppendFormat (", {0}", pairs [++i].Trim ());

          DateTime expires;
          if (!DateTime.TryParseExact (
            buffer.ToString (),
            new [] { "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'", "r" },
            CultureInfo.CreateSpecificCulture ("en-US"),
            DateTimeStyles.AdjustToUniversal | DateTimeStyles.replacedumeUniversal,
            out expires))
            expires = DateTime.Now;

          if (cookie != null && cookie.Expires == DateTime.MinValue)
            cookie.Expires = expires.ToLocalTime ();
        }
        else if (pair.StartsWith ("max-age", StringComparison.InvariantCultureIgnoreCase)) {
          var max = Int32.Parse (pair.GetValueInternal ("=").Trim ('"'));
          var expires = DateTime.Now.AddSeconds ((double) max);
          if (cookie != null)
            cookie.Expires = expires;
        }
        else if (pair.StartsWith ("path", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Path = pair.GetValueInternal ("=");
        }
        else if (pair.StartsWith ("domain", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Domain = pair.GetValueInternal ("=");
        }
        else if (pair.StartsWith ("port", StringComparison.InvariantCultureIgnoreCase)) {
          var port = pair.Equals ("port", StringComparison.InvariantCultureIgnoreCase)
                     ? "\"\""
                     : pair.GetValueInternal ("=");

          if (cookie != null)
            cookie.Port = port;
        }
        else if (pair.StartsWith ("comment", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Comment = pair.GetValueInternal ("=").UrlDecode ();
        }
        else if (pair.StartsWith ("commenturl", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.CommentUri = pair.GetValueInternal ("=").Trim ('"').ToUri ();
        }
        else if (pair.StartsWith ("discard", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Discard = true;
        }
        else if (pair.StartsWith ("secure", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Secure = true;
        }
        else if (pair.StartsWith ("httponly", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.HttpOnly = true;
        }
        else {
          if (cookie != null)
            cookies.Add (cookie);

          string name;
          string val = String.Empty;

          var pos = pair.IndexOf ('=');
          if (pos == -1) {
            name = pair;
          }
          else if (pos == pair.Length - 1) {
            name = pair.Substring (0, pos).TrimEnd (' ');
          }
          else {
            name = pair.Substring (0, pos).TrimEnd (' ');
            val = pair.Substring (pos + 1).TrimStart (' ');
          }

          cookie = new Cookie (name, val);
        }
      }

      if (cookie != null)
        cookies.Add (cookie);

      return cookies;
    }

19 Source : NetworkInterface.cs
with GNU General Public License v3.0
from BornToBeRoot

public static List<NetworkInterfaceInfo> GetNetworkInterfaces()
        {
            var listNetworkInterfaceInfo = new List<NetworkInterfaceInfo>();

            foreach (var networkInterface in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
            {
                // NetworkInterfaceType 53 is proprietary virtual/internal interface
                // https://docs.microsoft.com/en-us/windows-hardware/drivers/network/ndis-interface-types
                if (networkInterface.NetworkInterfaceType != NetworkInterfaceType.Ethernet && networkInterface.NetworkInterfaceType != NetworkInterfaceType.Wireless80211 && (int)networkInterface.NetworkInterfaceType != 53)
                    continue;

                var listIPv4Address = new List<Tuple<IPAddress, IPAddress>>();
                var listIPv6AddressLinkLocal = new List<IPAddress>();
                var listIPv6Address = new List<IPAddress>();

                var dhcpLeaseObtained = new DateTime();
                var dhcpLeaseExpires = new DateTime();

                var ipProperties = networkInterface.GetIPProperties();

                foreach (var unicastIPAddrInfo in ipProperties.UnicastAddresses)
                {
                    switch (unicastIPAddrInfo.Address.AddressFamily)
                    {
                        case AddressFamily.InterNetwork:

                            listIPv4Address.Add(new Tuple<IPAddress, IPAddress>(unicastIPAddrInfo.Address, unicastIPAddrInfo.IPv4Mask));
                            dhcpLeaseExpires = (DateTime.UtcNow + TimeSpan.FromSeconds(unicastIPAddrInfo.AddressPreferredLifetime)).ToLocalTime();
                            dhcpLeaseObtained = (DateTime.UtcNow + TimeSpan.FromSeconds(unicastIPAddrInfo.AddressValidLifetime) - TimeSpan.FromSeconds(unicastIPAddrInfo.DhcpLeaseLifetime)).ToLocalTime();
                            break;
                        case AddressFamily.InterNetworkV6 when unicastIPAddrInfo.Address.IsIPv6LinkLocal:
                            listIPv6AddressLinkLocal.Add(unicastIPAddrInfo.Address);
                            break;
                        case AddressFamily.InterNetworkV6:
                            listIPv6Address.Add(unicastIPAddrInfo.Address);
                            break;
                    }
                }

                var listIPv4Gateway = new List<IPAddress>();
                var listIPv6Gateway = new List<IPAddress>();

                foreach (var gatewayIPAddrInfo in ipProperties.GatewayAddresses)
                {
                    switch (gatewayIPAddrInfo.Address.AddressFamily)
                    {
                        case AddressFamily.InterNetwork:
                            listIPv4Gateway.Add(gatewayIPAddrInfo.Address);
                            break;
                        case AddressFamily.InterNetworkV6:
                            listIPv6Gateway.Add(gatewayIPAddrInfo.Address);
                            break;
                    }
                }

                var listDhcpServer = new List<IPAddress>();

                foreach (var dhcpServerIPAddress in ipProperties.DhcpServerAddresses)
                {
                    if (dhcpServerIPAddress.AddressFamily == AddressFamily.InterNetwork)
                        listDhcpServer.Add(dhcpServerIPAddress);
                }

                // Check if autoconfiguration for DNS is enabled (only via registry key)
                var nameServerKey = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{networkInterface.Id}");
                var dnsAutoconfigurationEnabled = nameServerKey?.GetValue("NameServer") != null && string.IsNullOrEmpty(nameServerKey.GetValue("NameServer").ToString());

                var listDNSServer = new List<IPAddress>();

                foreach (var dnsServerIPAddress in ipProperties.DnsAddresses)
                {
                    listDNSServer.Add(dnsServerIPAddress);
                }

                // Check if IPv4 protocol is available
                var ipv4ProtocolAvailable = true;
                IPv4InterfaceProperties ipv4Properties = null;

                try
                {
                    ipv4Properties = ipProperties.GetIPv4Properties();
                }
                catch (NetworkInformationException)
                {
                    ipv4ProtocolAvailable = false;
                }

                // Check if IPv6 protocol is available
                var ipv6ProtocolAvailable = true;
                IPv6InterfaceProperties ipv6Properties = null;

                try
                {
                    ipv6Properties = ipProperties.GetIPv6Properties();
                }
                catch (NetworkInformationException)
                {
                    ipv6ProtocolAvailable = false;
                }

                listNetworkInterfaceInfo.Add(new NetworkInterfaceInfo
                {
                    Id = networkInterface.Id,
                    Name = networkInterface.Name,
                    Description = networkInterface.Description,
                    Type = networkInterface.NetworkInterfaceType.ToString(),
                    PhysicalAddress = networkInterface.GetPhysicalAddress(),
                    Status = networkInterface.OperationalStatus,
                    IsOperational = networkInterface.OperationalStatus == OperationalStatus.Up,
                    Speed = networkInterface.Speed,
                    IPv4ProtocolAvailable = ipv4ProtocolAvailable,
                    IPv4Address = listIPv4Address.ToArray(),
                    IPv4Gateway = listIPv4Gateway.ToArray(),
                    DhcpEnabled = ipv4Properties != null && ipv4Properties.IsDhcpEnabled,
                    DhcpServer = listDhcpServer.ToArray(),
                    DhcpLeaseObtained = dhcpLeaseObtained,
                    DhcpLeaseExpires = dhcpLeaseExpires,
                    IPv6ProtocolAvailable = ipv6ProtocolAvailable,
                    IPv6AddressLinkLocal = listIPv6AddressLinkLocal.ToArray(),
                    IPv6Address = listIPv6Address.ToArray(),
                    IPv6Gateway = listIPv6Gateway.ToArray(),
                    DNSAutoconfigurationEnabled = dnsAutoconfigurationEnabled,
                    DNSSuffix = ipProperties.DnsSuffix,
                    DNSServer = listDNSServer.ToArray()
                });
            }

            return listNetworkInterfaceInfo;
        }

19 Source : ActivatedJob.cs
with Apache License 2.0
from camunda-community-hub

private static DateTime FromUTCTimestamp(long milliseconds)
        {
            DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            dtDateTime = dtDateTime.AddMilliseconds(milliseconds).ToLocalTime();
            return dtDateTime;
        }

19 Source : BusinessUser.cs
with MIT License
from Cankirism

private UsersProperties GetUserProperties(DirectoryEntry de)
        {
            SearchResult searchResult = user.SetSearchResult(de);
            var usersProperties = new UsersProperties();
            usersProperties.cannonicalName = de.Properties["cn"].Value.ToString();
            usersProperties.samAccountName = de.Properties["samaccountname"][0].ToString();
            usersProperties.userAccountControlCode = de.Properties["useraccountcontrol"][0].ToString();
            usersProperties.userAccountControl = UserAccountControl(Convert.ToInt32(de.Properties["useraccountcontrol"][0]));
            usersProperties.whenCreated = Convert.ToDateTime(de.Properties["whenCreated"].Value).ToLocalTime().ToString();
            usersProperties.pwdLastSet = DateTime.FromFileTime((long)searchResult.Properties["pwdLastSet"][0]).ToShortDateString();
            usersProperties.lastLogon = DateTime.FromFileTime((long)searchResult.Properties["lastLogon"][0]).ToLocalTime().ToString();
            return usersProperties;

        }

19 Source : QUERY_FILE_INFO.cs
with Apache License 2.0
from caozhiyuan

public void ParseBuffer(byte[] responseBytes, int length)
        {
            this.FileSize = Util.BufferToLong(responseBytes, 0);
            DateTime dateTime = new DateTime(1970, 1, 1);
            this.CreateTime = dateTime.AddSeconds(Util.BufferToLong(responseBytes, 8)).ToLocalTime();
            this.Crc32 = Util.BufferToLong(responseBytes, 16);
        }

19 Source : LogReader.cs
with MIT License
from carina-studio

void ReadLog(LogBuilder logBuilder, Match match, StringPool stringPool, string[]? timestampFormats)
		{
			foreach (Group group in match.Groups)
			{
				if (!group.Success)
					continue;
				var name = group.Name;
				if (name == "0")
					continue;
				var value = group.Value.Let(it =>
				{
					if (it.Length == 0)
						return it;
					return this.logStringEncoding switch
					{
						LogStringEncoding.Json => JsonUtility.DecodeFromJsonString(it.TrimEnd()),
						LogStringEncoding.Xml => WebUtility.HtmlDecode(it.TrimEnd()),
						_ => it.TrimEnd(),
					};
				});
				if (Log.HasMultiLineStringProperty(name))
					logBuilder.AppendToNextLine(name, value);
				else if (Log.HreplacedtringProperty(name))
				{
					switch (name)
					{
						case nameof(Log.Category):
						case nameof(Log.DeviceId):
						case nameof(Log.DeviceName):
						case nameof(Log.Event):
						case nameof(Log.ProcessId):
						case nameof(Log.ProcessName):
						case nameof(Log.SourceName):
						case nameof(Log.ThreadId):
						case nameof(Log.ThreadName):
						case nameof(Log.UserId):
						case nameof(Log.UserName):
							logBuilder.Set(name, stringPool[value]);
							break;
						default:
							logBuilder.Set(name, value);
							break;
					}
				}
				else if (Log.HasDateTimeProperty(name))
				{
					switch (this.timestampEncoding)
					{
						case LogTimestampEncoding.Custom:
							if (timestampFormats != null)
							{
								for (var i = timestampFormats.Length - 1; i >= 0; --i)
								{
									if (DateTime.TryParseExact(value, timestampFormats[i], this.timestampCultureInfo, DateTimeStyles.None, out var timestamp))
									{
										logBuilder.Set(name, timestamp.ToBinary().ToString());
										break;
									}
								}
							}
							else
								logBuilder.Set(name, value);
							break;
						case LogTimestampEncoding.Unix:
							if (long.TryParse(value, out var sec))
								logBuilder.Set(name, (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(sec).ToLocalTime()).ToBinary().ToString());
							break;
						case LogTimestampEncoding.UnixMicroseconds:
							if (long.TryParse(value, out var us))
								logBuilder.Set(name, (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(us / 1000).ToLocalTime()).ToBinary().ToString());
							break;
						case LogTimestampEncoding.UnixMilliseconds:
							if (long.TryParse(value, out var ms))
								logBuilder.Set(name, (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(ms).ToLocalTime()).ToBinary().ToString());
							break;
					}
				}
				else if (name == nameof(Log.Level))
				{
					if (this.logLevelMap.TryGetValue(value, out var level))
						logBuilder.Set(name, level.ToString());
				}
				else
					logBuilder.Set(name, value);
			}

19 Source : unixtime.cs
with MIT License
from ccxt-net

public static DateTime ConvertToLocalTime(string timeWithZone)
        {
            return ConvertToUtcTime(timeWithZone).ToLocalTime();
        }

19 Source : unixtime.cs
with MIT License
from ccxt-net

public static DateTime ConvertToLocalTimeMilli(Int64 milliSeconds)
        {
            return ConvertToUtcTimeMilli(milliSeconds).ToLocalTime();
        }

19 Source : unixtime.cs
with MIT License
from ccxt-net

public static string ToLocalTimeString(DateTime localtime)
        {
            return localtime.ToLocalTime().ToDateTimeString();
        }

19 Source : unixtime.cs
with MIT License
from ccxt-net

public static DateTime ConvertToLocalTime(Int64 seconds)
        {
            return ConvertToUtcTime(seconds).ToLocalTime();
        }

19 Source : CookieCollection.cs
with GNU General Public License v2.0
from Cdorey

private static CookieCollection parseResponse (string value)
    {
      var cookies = new CookieCollection ();

      Cookie cookie = null;
      var pairs = splitCookieHeaderValue (value);
      for (var i = 0; i < pairs.Length; i++) {
        var pair = pairs[i].Trim ();
        if (pair.Length == 0)
          continue;

        if (pair.StartsWith ("version", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Version = Int32.Parse (pair.GetValue ('=', true));
        }
        else if (pair.StartsWith ("expires", StringComparison.InvariantCultureIgnoreCase)) {
          var buff = new StringBuilder (pair.GetValue ('='), 32);
          if (i < pairs.Length - 1)
            buff.AppendFormat (", {0}", pairs[++i].Trim ());

          DateTime expires;
          if (!DateTime.TryParseExact (
            buff.ToString (),
            new[] { "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'", "r" },
            CultureInfo.CreateSpecificCulture ("en-US"),
            DateTimeStyles.AdjustToUniversal | DateTimeStyles.replacedumeUniversal,
            out expires))
            expires = DateTime.Now;

          if (cookie != null && cookie.Expires == DateTime.MinValue)
            cookie.Expires = expires.ToLocalTime ();
        }
        else if (pair.StartsWith ("max-age", StringComparison.InvariantCultureIgnoreCase)) {
          var max = Int32.Parse (pair.GetValue ('=', true));
          var expires = DateTime.Now.AddSeconds ((double) max);
          if (cookie != null)
            cookie.Expires = expires;
        }
        else if (pair.StartsWith ("path", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Path = pair.GetValue ('=');
        }
        else if (pair.StartsWith ("domain", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Domain = pair.GetValue ('=');
        }
        else if (pair.StartsWith ("port", StringComparison.InvariantCultureIgnoreCase)) {
          var port = pair.Equals ("port", StringComparison.InvariantCultureIgnoreCase)
                     ? "\"\""
                     : pair.GetValue ('=');

          if (cookie != null)
            cookie.Port = port;
        }
        else if (pair.StartsWith ("comment", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Comment = pair.GetValue ('=').UrlDecode ();
        }
        else if (pair.StartsWith ("commenturl", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.CommentUri = pair.GetValue ('=', true).ToUri ();
        }
        else if (pair.StartsWith ("discard", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Discard = true;
        }
        else if (pair.StartsWith ("secure", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.Secure = true;
        }
        else if (pair.StartsWith ("httponly", StringComparison.InvariantCultureIgnoreCase)) {
          if (cookie != null)
            cookie.HttpOnly = true;
        }
        else {
          if (cookie != null)
            cookies.Add (cookie);

          string name;
          string val = String.Empty;

          var pos = pair.IndexOf ('=');
          if (pos == -1) {
            name = pair;
          }
          else if (pos == pair.Length - 1) {
            name = pair.Substring (0, pos).TrimEnd (' ');
          }
          else {
            name = pair.Substring (0, pos).TrimEnd (' ');
            val = pair.Substring (pos + 1).TrimStart (' ');
          }

          cookie = new Cookie (name, val);
        }
      }

      if (cookie != null)
        cookies.Add (cookie);

      return cookies;
    }

19 Source : Client.cs
with Apache License 2.0
from cdy816

public bool Login(string username,string preplacedword)
        {
            if (mSecurityClient != null)
            {
                try
                {
                    var re = mSecurityClient.Login(new LoginRequest() { Name = username, Preplacedword = preplacedword });
                    TimeOut = re.Timeout;
                    LoginTime = DateTime.FromBinary(re.Time).ToLocalTime();
                    mLoginId = re.Token;
                }
                catch
                {
                    return false;
                }
            }
            return false;
        }

19 Source : RealDataController.cs
with Apache License 2.0
from cdy816

[HttpGet()]
        public RealValueQueryResponse Get([FromBody] RealDataRequest request)
        {
            if(DbInRunWebApi.SecurityManager.Manager.IsLogin(request.Token)&&DbInRunWebApi.SecurityManager.Manager.CheckReaderPermission(request.Token,request.Group))
            {
                RealValueQueryResponse response = new RealValueQueryResponse() { Result = true, Datas = new List<RealValue>(request.TagNames.Count) };
                var service = ServiceLocator.Locator.Resolve<IRealTagConsumer>();
                var ids = service.GetTagIdByName(request.TagNames.Select(e=>string.IsNullOrEmpty(request.Group)?e:request.Group+"."+e).ToList());
                for (int i = 0; i < request.TagNames.Count; i++)
                {
                    if (ids[i].HasValue)
                    {
                        byte quality;
                        DateTime time;
                        byte tagtype = 0;
                        var val = service.GetTagValue(ids[i].Value, out quality, out time, out tagtype);
                        response.Datas.Add(new RealValue() { Quality = quality, Time = time.ToLocalTime(), Value = val });
                    }
                }
                return response;
            }
            //ServiceLocator.Locator.Resolve<IRealTagComsumer>().GetTagValue()
            return new RealValueQueryResponse() { Result = false };
        }

19 Source : MainWindow.xaml.cs
with Apache License 2.0
from cdy816

private void hisDataWrite_Click(object sender, RoutedEventArgs e)
        {
            List<TagValue> vals = new List<TagValue>();
            DateTime dt = DateTime.UtcNow.AddSeconds(-30000);

            StringBuilder sb = new StringBuilder();
            sb.Append(dt.ToLocalTime().ToString() + "   " + DateTime.Now.ToString());

            Random rd = new Random((int)dt.Ticks);
            double dval = rd.NextDouble();
            for(int i=0;i<30000;i++)
            {
                vals.Add(new TagValue() { Quality = 0, Time = dt.AddSeconds(i), Value = dval+i*1.0/10 });
            }
            //for(int i=6;i<7;i++)
            driverProxy.SetTagHisValue(int.Parse(Hid.Text), TagType.Double, vals);

            MessageBox.Show(sb.ToString());

        }

19 Source : Logger.cs
with GNU General Public License v3.0
from chaincase-app

public static void Log(LogLevel level, string message, int additionalEntrySeparators = 0, bool additionalEntrySeparatorsLogFileOnlyMode = true, [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1)
		{
			try
			{
				if (Modes.Count == 0 || !IsOn())
				{
					return;
				}

				if (level < MinimumLevel)
				{
					return;
				}

				message = Guard.Correct(message);
				var category = string.IsNullOrWhiteSpace(callerFilePath) ? "" : $"{EnvironmentHelpers.ExtractFileName(callerFilePath)} ({callerLineNumber})";

				var messageBuilder = new StringBuilder();
				messageBuilder.Append($"{DateTime.UtcNow.ToLocalTime():yyyy-MM-dd HH:mm:ss} {level.ToString().ToUpperInvariant()}\t");

				if (message.Length == 0)
				{
					if (category.Length == 0) // If both empty. It probably never happens though.
					{
						messageBuilder.Append($"{EntrySeparator}");
					}
					else // If only the message is empty.
					{
						messageBuilder.Append($"{category}{EntrySeparator}");
					}
				}
				else
				{
					if (category.Length == 0) // If only the category is empty.
					{
						messageBuilder.Append($"{message}{EntrySeparator}");
					}
					else // If none of them empty.
					{
						messageBuilder.Append($"{category}\t{message}{EntrySeparator}");
					}
				}

				var finalMessage = messageBuilder.ToString();

				for (int i = 0; i < additionalEntrySeparators; i++)
				{
					messageBuilder.Insert(0, EntrySeparator);
				}

				var finalFileMessage = messageBuilder.ToString();
				if (!additionalEntrySeparatorsLogFileOnlyMode)
				{
					finalMessage = finalFileMessage;
				}

				lock (Lock)
				{
					if (Modes.Contains(LogMode.Console))
					{
						lock (Console.Out)
						{
							var color = Console.ForegroundColor;
							switch (level)
							{
								case LogLevel.Warning:
									color = ConsoleColor.Yellow;
									break;

								case LogLevel.Error:
								case LogLevel.Critical:
									color = ConsoleColor.Red;
									break;

								default:
									break; // Keep original color.
							}

							Console.ForegroundColor = color;
							Console.Write(finalMessage);
							Console.ResetColor();
						}
					}

					if (Modes.Contains(LogMode.Console))
					{
						Debug.Write(finalMessage);
					}

					if (!Modes.Contains(LogMode.File))
					{
						return;
					}

					IoHelpers.EnsureContainingDirectoryExists(FilePath);

					if (File.Exists(FilePath))
					{
						var sizeInBytes = new FileInfo(FilePath).Length;
						if (sizeInBytes > 1000 * MaximumLogFileSize)
						{
							File.Delete(FilePath);
						}
					}

					File.AppendAllText(FilePath, finalFileMessage);
				}
			}
			catch (Exception ex)
			{
				if (Interlocked.Increment(ref LoggingFailedCount) == 1) // If it only failed the first time, try log the failure.
				{
					LogDebug($"Logging failed: {ex}");
				}

				// If logging the failure is successful then clear the failure counter.
				// If it's not the first time the logging failed, then we do not try to log logging failure, so clear the failure counter.
				Interlocked.Exchange(ref LoggingFailedCount, 0);
			}
		}

19 Source : ChaumianCoinJoinController.cs
with GNU General Public License v3.0
from chaincase-app

private static void TryLogLateRequest(long roundId, RoundPhase desiredPhase)
		{
			try
			{
				DateTimeOffset ended = CoordinatorRound.PhaseTimeoutLog.TryGet((roundId, desiredPhase));
				if (ended != default)
				{
					Logger.LogInfo($"{DateTime.UtcNow.ToLocalTime():yyyy-MM-dd HH:mm:ss} {desiredPhase} {(int)(DateTimeOffset.UtcNow - ended).TotalSeconds} seconds late.");
				}
			}
			catch (Exception ex)
			{
				Logger.LogDebug(ex);
			}
		}

19 Source : Main.cs
with MIT License
from ChendoChap

private SearchEntry[] Find(SceSaveDataDirNameSearchCond searchCond, SceSaveDataDirNameSearchResult searchResult)
        {
            var searchCondAddr = ps4.AllocateMemory(pid, Marshal.SizeOf(typeof(SceSaveDataDirNameSearchCond)) + Marshal.SizeOf(typeof(SceSaveDataDirNameSearchResult)));
            var searchResultAddr = searchCondAddr + (uint)Marshal.SizeOf(typeof(SceSaveDataDirNameSearchCond));

            ps4.WriteMemory(pid, searchCondAddr, searchCond);
            ps4.WriteMemory(pid, searchResultAddr, searchResult);
            var ret = ps4.Call(pid, stub, libSceSaveDataBase + offsets.sceSaveDataDirNameSearch, searchCondAddr, searchResultAddr);
            WriteLog($"sceSaveDataDirNameSearch ret = 0x{ret:X}");
            if ( ret == 0)
            {
                searchResult = ps4.ReadMemory<SceSaveDataDirNameSearchResult>(pid, searchResultAddr);
                SearchEntry[] sEntries = new SearchEntry[searchResult.hitNum];
                var paramMemory = ps4.ReadMemory(pid, searchResult.param, (int)searchResult.hitNum * Marshal.SizeOf(typeof(SceSaveDataParam)));
                var dirNamesMemory = ps4.ReadMemory(pid, searchResult.dirNames, (int)searchResult.hitNum * 32);
                for (int i = 0; i < searchResult.hitNum; i++)
                {
                    SceSaveDataParam tmp = (SceSaveDataParam)PS4DBG.GetObjectFromBytes(PS4DBG.SubArray(paramMemory, i * Marshal.SizeOf(typeof(SceSaveDataParam)), Marshal.SizeOf(typeof(SceSaveDataParam))), typeof(SceSaveDataParam));
                    sEntries[i] = new SearchEntry
                    {
                        dirName = System.Text.Encoding.UTF8.GetString(PS4DBG.SubArray(dirNamesMemory, i * 32, 32)),
                        replacedle = System.Text.Encoding.UTF8.GetString(tmp.replacedle),
                        subreplacedle = System.Text.Encoding.UTF8.GetString(tmp.subreplacedle),
                        detail = System.Text.Encoding.UTF8.GetString(tmp.detail),
                        time = new DateTime(1970, 1, 1).ToLocalTime().AddSeconds(tmp.mtime).ToString(),
                    };
                }
                ps4.FreeMemory(pid, searchCondAddr, Marshal.SizeOf(typeof(SceSaveDataDirNameSearchCond)) + Marshal.SizeOf(typeof(SceSaveDataDirNameSearchResult)));
                return sEntries;
            }

            ps4.FreeMemory(pid, searchCondAddr, Marshal.SizeOf(typeof(SceSaveDataDirNameSearchCond)) + Marshal.SizeOf(typeof(SceSaveDataDirNameSearchResult)));

            return new SearchEntry[0];

        }

19 Source : DataStream.Read.cs
with GNU General Public License v2.0
from CHKZL

public DateTime ReadDateTimeUtc()
        {
            return new DateTime((ReadLong() + UNIX_OFFSET) * 10).ToLocalTime();
        }

19 Source : LibraryHelper.cs
with GNU General Public License v3.0
from CircuitLord

public DateTime UnixTimeStampToDateTime( double unixTimeStamp ) {
			return epoch.AddSeconds( unixTimeStamp ).ToLocalTime();
		}

19 Source : DatetimeLocalInputType.cs
with GNU General Public License v3.0
from CircuitLord

public override String ConvertFromDate(DateTime value)
        {
            value = value.ToLocalTime();
            var date = String.Format(CultureInfo.InvariantCulture, "{0:0000}-{1:00}-{2:00}", value.Year, value.Month, value.Day);
            var time = String.Format(CultureInfo.InvariantCulture, "{0:00}:{1:00}:{2:00},{3:000}", value.Hour, value.Minute, value.Second, value.Millisecond);
            return String.Concat(date, "T", time);
        }

19 Source : UtcToLocalDateTimeConverter.cs
with GNU General Public License v3.0
from CitizensReactor

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DateTime datetime;

            if (value is DateTime)
            {
                datetime = ((DateTime)value).ToLocalTime();
            }
            else
            {
                datetime = DateTime.Parse(value?.ToString()).ToLocalTime();
            }

            var resultTime = TimeZone.CurrentTimeZone.ToLocalTime(datetime);
            var resultString = resultTime.ToString();
            return resultString;
        }

19 Source : Clock.cs
with GNU Lesser General Public License v3.0
from cnAbp

public virtual DateTime Normalize(DateTime dateTime)
        {
            if (Kind == DateTimeKind.Unspecified || Kind == dateTime.Kind)
            {
                return dateTime;
            }

            if (Kind == DateTimeKind.Local && dateTime.Kind == DateTimeKind.Utc)
            {
                return dateTime.ToLocalTime();
            }

            if (Kind == DateTimeKind.Utc && dateTime.Kind == DateTimeKind.Local)
            {
                return dateTime.ToUniversalTime();
            }

            return DateTime.SpecifyKind(dateTime, Kind);
        }

19 Source : DateTimeUtilTest.cs
with MIT License
from cocosip

[Fact]
        public void ToInt32_FromInt32_Test()
        {
            var dateTime = DateTime.Now.ToLocalTime();
            var int32DateTime = DateTimeUtil.ToInt32(dateTime);
            replacedert.True(int32DateTime > 0);
            var dateTime2 = DateTimeUtil.ToDateTime(int32DateTime);

            var dvalue = dateTime2 - dateTime;
            replacedert.True(dvalue.TotalSeconds < 1);

            var int32DateTime2 = DateTimeUtil.ToInt32(dateTime.ToString("yyyy-MM-dd hh:mm:ss"), 0);
            var dateTime3 = DateTimeUtil.ToDateTime(int32DateTime2);

            //var dvalue2 = dateTime3 - dateTime;
            //replacedert.True(dvalue2.TotalSeconds < 2);

            var int32DateTime4 = DateTimeUtil.ToInt32("2019-08-12 111111", 33);
            replacedert.Equal(33, int32DateTime4);
        }

19 Source : RestApiCommon.cs
with Apache License 2.0
from cohesity

public static DateTime ConvertUsecsToDateTime(long usecs)
        {
            long unixTime = usecs / 1000000;
            DateTime origin = DateTime.Parse("1970-01-01 00:00:00");
            return origin.AddSeconds(unixTime).ToLocalTime();
        }

19 Source : Tools.cs
with GNU General Public License v3.0
from CommentViewerCollection

public static DateTime FromUnixTime(long unixTime)
        {
            // unix epochからunixTime秒だけ経過した時刻を求める
            return _unixEpoch.AddSeconds(unixTime).ToLocalTime();
        }

19 Source : XmlWritingTests.cs
with GNU General Public License v3.0
from CommentViewerCollection

[Test]
        public void IYouTubeCommentがXMLに正常に書き出されるか()
        {
            var optionsMock = new Mock<Options>();
            optionsMock.Setup(o => o.IsEnabled).Returns(true);

            var messageMetadataMock = new Mock<IMessageMetadata>();
            var pluginMock = new Mock<CommentGeneratorPlugin>() { CallBase = true };
            pluginMock.Protected().Setup<string>("CommentXmlPath").Returns(FilePath);
            pluginMock.Protected().Setup<Options>("Options").Returns(optionsMock.Object);
            pluginMock.Protected().Setup<bool>("IsHcgSettingFileExists").Returns(true);
            pluginMock.Protected().Setup<DateTime>("GetCurrentDateTime").Returns(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).ToLocalTime());

            var message = new YtComment()
            {
                NameItems = new List<IMessagePart> { Common.MessagePartFactory.CreateMessageText("name") },
                Commenreplacedems = new List<IMessagePart> { Common.MessagePartFactory.CreateMessageText("comment") },
            };
            var messageMetadata = messageMetadataMock.Object;


            var plugin = pluginMock.Object;
            plugin.OnMessageReceived(message, messageMetadata);
            plugin.Write();

            if (!File.Exists(FilePath))
            {
                replacedert.Fail();
            }

            string content;
            using (var sr = new System.IO.StreamReader(FilePath))
            {
                content = sr.ReadToEnd();
            }
            replacedert.AreEqual("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<log>\r\n  <comment no=\"0\" time=\"0\" owner=\"0\" service=\"youtubelive\" handle=\"name\">comment</comment>\r\n</log>", content);
        }

19 Source : Tools.cs
with GNU General Public License v3.0
from CommentViewerCollection

public static DateTime FromUnixTime(long unix)
        {
            var baseDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            var date = baseDate.AddSeconds(unix);
            return date.ToLocalTime();
        }

19 Source : InfoCommentViewModel.cs
with GNU General Public License v3.0
from CommentViewerCollection

private static DateTime UnixtimeToDateTime(long unixTimeStamp)
        {
            var dt = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
            return dt.AddSeconds(unixTimeStamp).ToLocalTime();
        }

See More Examples