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
19
View Source File : DateTimeExtensions.cs
License : MIT License
Project Creator : 1100100
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 : Server.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public DateTime LastSave() => Call("LASTSAVE", rt => rt.ThrowOrValue(a => _epoch.AddSeconds(a.ConvertTo<long>()).ToLocalTime()));
19
View Source File : Server.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public DateTime Time() => Call("TIME", rt => rt.ThrowOrValue((a, _) => _epoch.AddSeconds(a[0].ConvertTo<long>()).AddTicks(a[1].ConvertTo<long>() * 10).ToLocalTime()));
19
View Source File : StringHandlingPackets.cs
License : MIT License
Project Creator : 499116344
License : MIT License
Project Creator : 499116344
public void Add(DateTime datetime)
{
var value = (uint) (datetime - DateTime.Parse("1970-1-1").ToLocalTime()).TotalSeconds;
var bytes = BitConverter.GetBytes(value);
Array.Reverse(bytes);
_stream.Write(bytes, 0, bytes.Length);
}
19
View Source File : ChangesetConverter.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public IEnumerable<string> GetLogLines(Changeset changeset)
{
// Filter changeset Owner
if (!FilterByString(changeset.OwnerDisplayName ?? "", m_includeUsersWildcard, m_excludeUsersWildcard))
yield break;
foreach (var change in changeset.Changes)
{
{
// Filter files
if (!FilterByString(change.Item.ServerItem, m_includeFilesWildcard, m_excludeFilesWildcard))
continue;
}
var changeTypeCode = GetChangeType(change.ChangeType);
if (changeTypeCode == null)
continue;
double unixTime = (int)(changeset.CreationDate - st_unixTimeZero.ToLocalTime()).TotalSeconds;
var userName = changeset.OwnerDisplayName;
var fileName = FormatFileName(change.Item.ServerItem);
yield return
string.Format(CultureInfo.InvariantCulture, "{0}|{1}|{2}|{3}",
unixTime,
userName,
changeTypeCode,
fileName);
}
}
19
View Source File : Corpse.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
protected override void OnInitialInventoryLoadCompleted()
{
if (Level.HasValue)
{
var dtTimeToRot = DateTime.UtcNow.AddSeconds(TimeToRot ?? 0);
var tsDecay = dtTimeToRot - DateTime.UtcNow;
log.Debug($"[CORPSE] {Name} (0x{Guid}) Reloaded from Database: Corpse Level: {Level ?? 0} | InventoryLoaded: {InventoryLoaded} | Inventory.Count: {Inventory.Count} | TimeToRot: {TimeToRot} | CreationTimestamp: {CreationTimestamp} ({Time.GetDateTimeFromTimestamp(CreationTimestamp ?? 0).ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss")}) | Corpse should not decay before: {dtTimeToRot.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss")}, {tsDecay.ToString("%d")} day(s), {tsDecay.ToString("%h")} hours, {tsDecay.ToString("%m")} minutes, and {tsDecay.ToString("%s")} seconds from now.");
}
}
19
View Source File : Corpse.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public void RecalculateDecayTime(Player player)
{
// empty corpses decay faster
if (Inventory.Count == 0)
TimeToRot = EmptyDecayTime;
else
// a player corpse decays after 5 mins * playerLevel with a minimum of 1 hour
TimeToRot = Math.Max(3600, (player.Level ?? 1) * 300);
var dtTimeToRot = DateTime.UtcNow.AddSeconds(TimeToRot ?? 0);
var tsDecay = dtTimeToRot - DateTime.UtcNow;
Level = player.Level ?? 1;
log.Debug($"[CORPSE] {Name}.RecalculateDecayTime({player.Name}) 0x{Guid}: Player Level: {player.Level} | Inventory.Count: {Inventory.Count} | TimeToRot: {TimeToRot} | CreationTimestamp: {CreationTimestamp} ({Time.GetDateTimeFromTimestamp(CreationTimestamp ?? 0).ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss")}) | Corpse should not decay before: {dtTimeToRot.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss")}, {tsDecay.ToString("%d")} day(s), {tsDecay.ToString("%h")} hours, {tsDecay.ToString("%m")} minutes, and {tsDecay.ToString("%s")} seconds from now.");
}
19
View Source File : SolarViewsViewModel.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
public void OK()
{
if (model.CreatereplacedysisView) {
TryClose(true);
} else {
var log = new ModelSetupWizard.TransactionLog(CurrentModeSummary);
model.StartTime = SelectedStartTime.ToLocalTime();
model.EndTime = SelectedEndTime.ToLocalTime();
model.ExportTimeInterval = SelectedInterval;
model.Go(log);
SCaddinsApp.WindowManager.ShowMessageBox(log.Summary());
DockablePaneId docablePaneId = DockablePanes.BuiltInDockablePanes.ProjectBrowser;
DockablePane dP = new DockablePane(docablePaneId);
dP.Show();
}
}
19
View Source File : DateFilters.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static DateTime? DateToLocal(DateTime? date)
{
return date.HasValue
? date.Value.ToLocalTime()
: (DateTime?)null;
}
19
View Source File : SnowFlake.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
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 : BsonReader.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private void ReadType(BsonType type)
{
switch (type)
{
case BsonType.Number:
double d = ReadDouble();
if (_floatParseHandling == FloatParseHandling.Decimal)
{
SetToken(JsonToken.Float, Convert.ToDecimal(d, CultureInfo.InvariantCulture));
}
else
{
SetToken(JsonToken.Float, d);
}
break;
case BsonType.String:
case BsonType.Symbol:
SetToken(JsonToken.String, ReadLengthString());
break;
case BsonType.Object:
{
SetToken(JsonToken.StartObject);
ContainerContext newContext = new ContainerContext(BsonType.Object);
PushContext(newContext);
newContext.Length = ReadInt32();
break;
}
case BsonType.Array:
{
SetToken(JsonToken.StartArray);
ContainerContext newContext = new ContainerContext(BsonType.Array);
PushContext(newContext);
newContext.Length = ReadInt32();
break;
}
case BsonType.Binary:
BsonBinaryType binaryType;
byte[] data = ReadBinary(out binaryType);
object value = (binaryType != BsonBinaryType.Uuid)
? data
: (object)new Guid(data);
SetToken(JsonToken.Bytes, value);
break;
case BsonType.Undefined:
SetToken(JsonToken.Undefined);
break;
case BsonType.Oid:
byte[] oid = ReadBytes(12);
SetToken(JsonToken.Bytes, oid);
break;
case BsonType.Boolean:
bool b = Convert.ToBoolean(ReadByte());
SetToken(JsonToken.Boolean, b);
break;
case BsonType.Date:
long ticks = ReadInt64();
DateTime utcDateTime = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks);
DateTime dateTime;
switch (DateTimeKindHandling)
{
case DateTimeKind.Unspecified:
dateTime = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified);
break;
case DateTimeKind.Local:
dateTime = utcDateTime.ToLocalTime();
break;
default:
dateTime = utcDateTime;
break;
}
SetToken(JsonToken.Date, dateTime);
break;
case BsonType.Null:
SetToken(JsonToken.Null);
break;
case BsonType.Regex:
string expression = ReadString();
string modifiers = ReadString();
string regex = @"/" + expression + @"/" + modifiers;
SetToken(JsonToken.String, regex);
break;
case BsonType.Reference:
SetToken(JsonToken.StartObject);
_bsonReaderState = BsonReaderState.ReferenceStart;
break;
case BsonType.Code:
SetToken(JsonToken.String, ReadLengthString());
break;
case BsonType.CodeWScope:
SetToken(JsonToken.StartObject);
_bsonReaderState = BsonReaderState.CodeWScopeStart;
break;
case BsonType.Integer:
SetToken(JsonToken.Integer, (long)ReadInt32());
break;
case BsonType.TimeStamp:
case BsonType.Long:
SetToken(JsonToken.Integer, ReadInt64());
break;
default:
throw new ArgumentOutOfRangeException(nameof(type), "Unexpected BsonType value: " + type);
}
}
19
View Source File : DateTimeUtils.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private static bool TryParseDateTimeMicrosoft(StringReference text, DateTimeZoneHandling dateTimeZoneHandling, out DateTime dt)
{
long ticks;
TimeSpan offset;
DateTimeKind kind;
if (!TryParseMicrosoftDate(text, out ticks, out offset, out kind))
{
dt = default(DateTime);
return false;
}
DateTime utcDateTime = ConvertJavaScriptTicksToDateTime(ticks);
switch (kind)
{
case DateTimeKind.Unspecified:
dt = DateTime.SpecifyKind(utcDateTime.ToLocalTime(), DateTimeKind.Unspecified);
break;
case DateTimeKind.Local:
dt = utcDateTime.ToLocalTime();
break;
default:
dt = utcDateTime;
break;
}
dt = EnsureDateTime(dt, dateTimeZoneHandling);
return true;
}
19
View Source File : BsonBinaryWriter.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private void WriteTokenInternal(BsonToken t)
{
switch (t.Type)
{
case BsonType.Object:
{
BsonObject value = (BsonObject)t;
_writer.Write(value.CalculatedSize);
foreach (BsonProperty property in value)
{
_writer.Write((sbyte)property.Value.Type);
WriteString((string)property.Name.Value, property.Name.ByteCount, null);
WriteTokenInternal(property.Value);
}
_writer.Write((byte)0);
}
break;
case BsonType.Array:
{
BsonArray value = (BsonArray)t;
_writer.Write(value.CalculatedSize);
ulong index = 0;
foreach (BsonToken c in value)
{
_writer.Write((sbyte)c.Type);
WriteString(index.ToString(CultureInfo.InvariantCulture), MathUtils.IntLength(index), null);
WriteTokenInternal(c);
index++;
}
_writer.Write((byte)0);
}
break;
case BsonType.Integer:
{
BsonValue value = (BsonValue)t;
_writer.Write(Convert.ToInt32(value.Value, CultureInfo.InvariantCulture));
}
break;
case BsonType.Long:
{
BsonValue value = (BsonValue)t;
_writer.Write(Convert.ToInt64(value.Value, CultureInfo.InvariantCulture));
}
break;
case BsonType.Number:
{
BsonValue value = (BsonValue)t;
_writer.Write(Convert.ToDouble(value.Value, CultureInfo.InvariantCulture));
}
break;
case BsonType.String:
{
BsonString value = (BsonString)t;
WriteString((string)value.Value, value.ByteCount, value.CalculatedSize - 4);
}
break;
case BsonType.Boolean:
{
BsonValue value = (BsonValue)t;
_writer.Write((bool)value.Value);
}
break;
case BsonType.Null:
case BsonType.Undefined:
break;
case BsonType.Date:
{
BsonValue value = (BsonValue)t;
long ticks = 0;
if (value.Value is DateTime)
{
DateTime dateTime = (DateTime)value.Value;
if (DateTimeKindHandling == DateTimeKind.Utc)
{
dateTime = dateTime.ToUniversalTime();
}
else if (DateTimeKindHandling == DateTimeKind.Local)
{
dateTime = dateTime.ToLocalTime();
}
ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(dateTime, false);
}
#if !NET20
else
{
DateTimeOffset dateTimeOffset = (DateTimeOffset)value.Value;
ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(dateTimeOffset.UtcDateTime, dateTimeOffset.Offset);
}
#endif
_writer.Write(ticks);
}
break;
case BsonType.Binary:
{
BsonBinary value = (BsonBinary)t;
byte[] data = (byte[])value.Value;
_writer.Write(data.Length);
_writer.Write((byte)value.BinaryType);
_writer.Write(data);
}
break;
case BsonType.Oid:
{
BsonValue value = (BsonValue)t;
byte[] data = (byte[])value.Value;
_writer.Write(data);
}
break;
case BsonType.Regex:
{
BsonRegex value = (BsonRegex)t;
WriteString((string)value.Pattern.Value, value.Pattern.ByteCount, null);
WriteString((string)value.Options.Value, value.Options.ByteCount, null);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(t), "Unexpected token when writing BSON: {0}".FormatWith(CultureInfo.InvariantCulture, t.Type));
}
}
19
View Source File : DateTimeUtils.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private static DateTime SwitchToLocalTime(DateTime value)
{
switch (value.Kind)
{
case DateTimeKind.Unspecified:
return new DateTime(value.Ticks, DateTimeKind.Local);
case DateTimeKind.Utc:
return value.ToLocalTime();
case DateTimeKind.Local:
return value;
}
return value;
}
19
View Source File : DateTimeUtils.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
internal static bool TryParseDateTimeIso(StringReference text, DateTimeZoneHandling dateTimeZoneHandling, out DateTime dt)
{
DateTimeParser dateTimeParser = new DateTimeParser();
if (!dateTimeParser.Parse(text.Chars, text.StartIndex, text.Length))
{
dt = default(DateTime);
return false;
}
DateTime d = CreateDateTime(dateTimeParser);
long ticks;
switch (dateTimeParser.Zone)
{
case ParserTimeZone.Utc:
d = new DateTime(d.Ticks, DateTimeKind.Utc);
break;
case ParserTimeZone.LocalWestOfUtc:
{
TimeSpan offset = new TimeSpan(dateTimeParser.ZoneHour, dateTimeParser.ZoneMinute, 0);
ticks = d.Ticks + offset.Ticks;
if (ticks <= DateTime.MaxValue.Ticks)
{
d = new DateTime(ticks, DateTimeKind.Utc).ToLocalTime();
}
else
{
ticks += d.GetUtcOffset().Ticks;
if (ticks > DateTime.MaxValue.Ticks)
{
ticks = DateTime.MaxValue.Ticks;
}
d = new DateTime(ticks, DateTimeKind.Local);
}
break;
}
case ParserTimeZone.LocalEastOfUtc:
{
TimeSpan offset = new TimeSpan(dateTimeParser.ZoneHour, dateTimeParser.ZoneMinute, 0);
ticks = d.Ticks - offset.Ticks;
if (ticks >= DateTime.MinValue.Ticks)
{
d = new DateTime(ticks, DateTimeKind.Utc).ToLocalTime();
}
else
{
ticks += d.GetUtcOffset().Ticks;
if (ticks < DateTime.MinValue.Ticks)
{
ticks = DateTime.MinValue.Ticks;
}
d = new DateTime(ticks, DateTimeKind.Local);
}
break;
}
}
dt = EnsureDateTime(d, dateTimeZoneHandling);
return true;
}
19
View Source File : Bangumi.cs
License : MIT License
Project Creator : AlaricGilbert
License : MIT License
Project Creator : AlaricGilbert
public static List<BangumiInfo> GetBangumiInfos(BangumiSeason bseason)
{
var result = new List<BangumiInfo>();
for (int i = 0;i<bseason.Result.Count;i++)
{
var daySeason = bseason.Result[i];
for (int j=0;j<daySeason.Seasons.Count;j++)
{
var season = daySeason.Seasons[j];
if (season.Is_published == 1||season.Delay==1)
continue;
long pubts = season.Pub_ts;
pubts *= 10000000;
DateTime t = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
t = t.Add(new TimeSpan(pubts)).ToLocalTime();
Console.WriteLine(season.Pub_index);
var binfo = new BangumiInfo
{
Cover = season.Cover,
SquareCover = season.Square_cover,
Index = season.Pub_index.Substring(1, season.Pub_index.Length - 2),
EpNumber = Convert.ToInt32(season.Ep_id),
SeasonId = season.Season_id,
replacedle = season.replacedle,
UpdateTime = t
};
result.Add(binfo);
}
}
return result;
}
19
View Source File : DateTimeExtensions.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
public static DateTime EnsureLocal(this DateTime dateTime)
{
if(dateTime.Kind == DateTimeKind.Utc)
{
return dateTime.ToLocalTime();
}
return dateTime;
}
19
View Source File : JsonHelper.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
public static DateTime CreateDateTime(string value, bool UseUTCDateTime)
{
if (value.Length < 19)
return DateTime.MinValue;
bool utc = false;
// 0123456789012345678 9012 9/3
// datetime format = yyyy-MM-ddTHH:mm:ss .nnn Z
int year;
int month;
int day;
int hour;
int min;
int sec;
int ms = 0;
year = CreateInteger(value, 0, 4);
month = CreateInteger(value, 5, 2);
day = CreateInteger(value, 8, 2);
hour = CreateInteger(value, 11, 2);
min = CreateInteger(value, 14, 2);
sec = CreateInteger(value, 17, 2);
if (value.Length > 21 && value[19] == '.')
ms = CreateInteger(value, 20, 3);
if (value[value.Length - 1] == 'Z')
utc = true;
if (UseUTCDateTime == false && utc == false)
return new DateTime(year, month, day, hour, min, sec, ms);
else
return new DateTime(year, month, day, hour, min, sec, ms, DateTimeKind.Utc).ToLocalTime();
}
19
View Source File : TKeyRecord.cs
License : Apache License 2.0
Project Creator : alexreinert
License : Apache License 2.0
Project Creator : alexreinert
private static DateTime ParseDateTime(byte[] buffer, ref int currentPosition)
{
int timeStamp = DnsMessageBase.ParseInt(buffer, ref currentPosition);
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timeStamp).ToLocalTime();
}
19
View Source File : TSigRecord.cs
License : Apache License 2.0
Project Creator : alexreinert
License : Apache License 2.0
Project Creator : alexreinert
private static DateTime ParseDateTime(byte[] buffer, ref int currentPosition)
{
long timeStamp;
if (BitConverter.IsLittleEndian)
{
timeStamp = ((buffer[currentPosition++] << 40) | (buffer[currentPosition++] << 32) | buffer[currentPosition++] << 24 | (buffer[currentPosition++] << 16) | (buffer[currentPosition++] << 8) | buffer[currentPosition++]);
}
else
{
timeStamp = (buffer[currentPosition++] | (buffer[currentPosition++] << 8) | (buffer[currentPosition++] << 16) | (buffer[currentPosition++] << 24) | (buffer[currentPosition++] << 32) | (buffer[currentPosition++] << 40));
}
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timeStamp).ToLocalTime();
}
19
View Source File : AliyunSDKUtils.cs
License : MIT License
Project Creator : aliyunmq
License : MIT License
Project Creator : aliyunmq
public static DateTime ConvertFromUnixEpochSeconds(long milliSeconds)
{
return new DateTime(milliSeconds * 10000L + EPOCH_START.Ticks, DateTimeKind.Utc).ToLocalTime();
}
19
View Source File : TorrentInfo.cs
License : MIT License
Project Creator : aljazsim
License : MIT License
Project Creator : aljazsim
public static bool TryLoad(byte[] data, out TorrentInfo torrentInfo)
{
data.CannotBeNullOrEmpty();
BEncodedValue value;
BEncodedDictionary general;
BEncodedDictionary info;
List<TorrentFileInfo> files = new List<TorrentFileInfo>();
long pieceLength;
List<string> pieceHashes = new List<string>();
bool isPrivate = false;
Uri tmpUri;
List<Uri> announceList = new List<Uri>();
DateTime? creationDate = null;
string comment = null;
string createdBy = null;
Encoding encoding = Encoding.ASCII;
string filePath;
long fileLength = 0;
string fileHash;
string tmpString;
BEncodedString infoKey = new BEncodedString("info");
BEncodedString pieceLengthKey = new BEncodedString("piece length");
BEncodedString piecesKey = new BEncodedString("pieces");
BEncodedString privateKey = new BEncodedString("private");
BEncodedString nameKey = new BEncodedString("name");
BEncodedString lengthKey = new BEncodedString("length");
BEncodedString md5sumKey = new BEncodedString("md5sum");
BEncodedString filesKey = new BEncodedString("files");
BEncodedString pathKey = new BEncodedString("path");
BEncodedString announceKey = new BEncodedString("announce");
BEncodedString announceListKey = new BEncodedString("announce-list");
BEncodedString creationDateKey = new BEncodedString("creation date");
BEncodedString commentKey = new BEncodedString("comment");
BEncodedString createdByKey = new BEncodedString("created by");
BEncodedString encodingKey = new BEncodedString("encoding");
torrentInfo = null;
try
{
value = BEncodedValue.Decode(data);
}
catch (BEncodingException)
{
return false;
}
if (value is BEncodedDictionary)
{
general = value as BEncodedDictionary;
if (general.ContainsKey(infoKey) &&
general[infoKey] is BEncodedDictionary)
{
info = general[infoKey] as BEncodedDictionary;
// piece length
if (info.ContainsKey(pieceLengthKey) &&
info[pieceLengthKey] is BEncodedNumber)
{
pieceLength = info[pieceLengthKey].As<BEncodedNumber>().Number;
}
else
{
return false;
}
// pieces
if (info.ContainsKey(piecesKey) &&
info[piecesKey] is BEncodedString &&
info[piecesKey].As<BEncodedString>().TextBytes.Length % 20 == 0)
{
for (int i = 0; i < info[piecesKey].As<BEncodedString>().TextBytes.Length; i += 20)
{
byte[] tmpBytes = new byte[20];
Array.Copy(info[piecesKey].As<BEncodedString>().TextBytes, i, tmpBytes, 0, tmpBytes.Length);
pieceHashes.Add(tmpBytes.ToHexaDecimalString());
}
if (pieceHashes.Count == 0)
{
return false;
}
}
else
{
return false;
}
// is private
if (info.ContainsKey(privateKey) &&
info[privateKey] is BEncodedNumber)
{
isPrivate = info[privateKey].As<BEncodedNumber>().Number == 1;
}
// files
if (info.ContainsKey(nameKey) &&
info[nameKey] is BEncodedString &&
info.ContainsKey(lengthKey) &&
info[lengthKey] is BEncodedNumber)
{
// single file
filePath = info[nameKey].As<BEncodedString>().Text;
fileLength = info[lengthKey].As<BEncodedNumber>().Number;
if (info.ContainsKey(md5sumKey) &&
info[md5sumKey] is BEncodedString)
{
fileHash = info[md5sumKey].As<BEncodedString>().Text;
}
else
{
fileHash = null;
}
files.Add(new TorrentFileInfo(filePath, fileHash, fileLength));
}
else if (info.ContainsKey(nameKey) &&
info[nameKey] is BEncodedString &&
info.ContainsKey(filesKey) &&
info[filesKey] is BEncodedList)
{
tmpString = info[nameKey].As<BEncodedString>().Text;
// multi file
foreach (var item in info[filesKey].As<BEncodedList>())
{
if (item is BEncodedDictionary &&
item.As<BEncodedDictionary>().ContainsKey(pathKey) &&
item.As<BEncodedDictionary>()[pathKey] is BEncodedList &&
item.As<BEncodedDictionary>()[pathKey].As<BEncodedList>().All(x => x is BEncodedString) &&
item.As<BEncodedDictionary>().ContainsKey(lengthKey) &&
item.As<BEncodedDictionary>()[lengthKey] is BEncodedNumber)
{
filePath = Path.Combine(tmpString, Path.Combine(item.As<BEncodedDictionary>()[pathKey].As<BEncodedList>().Select(x => x.As<BEncodedString>().Text).ToArray()));
fileLength = item.As<BEncodedDictionary>()[lengthKey].As<BEncodedNumber>().Number;
if (item.As<BEncodedDictionary>().ContainsKey(md5sumKey) &&
item.As<BEncodedDictionary>()[md5sumKey] is BEncodedString)
{
fileHash = item.As<BEncodedDictionary>()[md5sumKey].As<BEncodedString>().Text;
}
else
{
fileHash = null;
}
files.Add(new TorrentFileInfo(filePath, fileHash, fileLength));
}
else
{
return false;
}
}
if (files.Count == 0)
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
// announce
if (general.ContainsKey(announceKey) &&
general[announceKey] is BEncodedString &&
Uri.TryCreate(general[announceKey].As<BEncodedString>().Text, UriKind.Absolute, out tmpUri))
{
announceList.Add(tmpUri);
}
else
{
return false;
}
// announce list
if (general.ContainsKey(announceListKey) &&
general[announceListKey] is BEncodedList)
{
foreach (var item in general[announceListKey].As<BEncodedList>())
{
if (item is BEncodedList)
{
foreach (var item2 in item.As<BEncodedList>())
{
if (Uri.TryCreate(item2.As<BEncodedString>().Text, UriKind.Absolute, out tmpUri))
{
announceList.Add(tmpUri);
}
}
}
}
announceList = announceList.Select(x => x.AbsoluteUri).Distinct().Select(x => new Uri(x)).ToList();
}
// creation adte
if (general.ContainsKey(creationDateKey) &&
general[creationDateKey] is BEncodedNumber)
{
creationDate = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(general[creationDateKey].As<BEncodedNumber>().Number).ToLocalTime();
}
// comment
if (general.ContainsKey(commentKey) &&
general[commentKey] is BEncodedString)
{
comment = general[commentKey].As<BEncodedString>().Text;
}
// created by
if (general.ContainsKey(createdByKey) &&
general[createdByKey] is BEncodedString)
{
createdBy = general[createdByKey].As<BEncodedString>().Text;
}
// encoding
if (general.ContainsKey(encodingKey) &&
general[encodingKey] is BEncodedString)
{
if (general[encodingKey].As<BEncodedString>().Text == "UTF8")
{
encoding = Encoding.UTF8;
}
}
torrentInfo = new TorrentInfo(
general,
info.Encode().CalculateSha1Hash().ToHexaDecimalString(),
pieceLength,
new ReadOnlyCollection<string>(pieceHashes),
isPrivate,
new ReadOnlyCollection<Uri>(announceList),
creationDate,
comment,
createdBy,
encoding,
new ReadOnlyCollection<TorrentFileInfo>(files));
return true;
}
else
{
return false;
}
}
19
View Source File : SnowflakeId.cs
License : MIT License
Project Creator : alonsoalon
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 : ExtensionMethods.cs
License : MIT License
Project Creator : Altevir
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 : CollabHistoryItemFactory.cs
License : MIT License
Project Creator : Alword
License : MIT License
Project Creator : Alword
private static DateTime TimeStampToDateTime(double timeStamp)
{
DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dateTime = dateTime.AddSeconds(timeStamp).ToLocalTime();
return dateTime;
}
19
View Source File : TimeExtensions.cs
License : GNU General Public License v3.0
Project Creator : Amazing-Favorites
License : GNU General Public License v3.0
Project Creator : Amazing-Favorites
public static DateTime ToLocalTime(this long time)
{
return DateTimeOffset.FromUnixTimeSeconds(time).DateTime.ToLocalTime();
}
19
View Source File : Scheduler.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
public int ScheduleAt(DateTime time, AnkhAction action)
{
if (action == null)
throw new ArgumentNullException("action");
if (time.Kind == DateTimeKind.Utc)
time = time.ToLocalTime();
lock (_actions)
{
while (_actions.ContainsKey(time))
time = time.Add(TimeSpan.FromMilliseconds(1));
ActionItem ai = new ActionItem(unchecked(++_nextActionId), action);
_actions.Add(time, ai);
Reschedule();
return ai.Id;
}
}
19
View Source File : PendingCommitItem.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
private string SafeDate(DateTime dateTime)
{
if (dateTime.Ticks == 0 || dateTime.Ticks == 1)
return "";
DateTime n = dateTime.ToLocalTime();
if (n < DateTime.Now - new TimeSpan(24, 0, 0))
return n.ToString("d");
else
return n.ToString("T");
}
19
View Source File : SynchronizeListItem.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
static string SafeDate(DateTime dateTime)
{
if (dateTime.Ticks == 0 || dateTime.Ticks == 1)
return "";
DateTime n = dateTime.ToLocalTime();
if (n < DateTime.Now - new TimeSpan(24, 0, 0))
return n.ToString("d");
else
return n.ToString("T");
}
19
View Source File : Utils.cs
License : MIT License
Project Creator : Analogy-LogViewer
License : MIT License
Project Creator : Analogy-LogViewer
public static DateTime GetOffsetTime(DateTime time)
{
return UserSettingsManager.UserSettings.TimeOffsetType switch
{
TimeOffsetType.None => time,
TimeOffsetType.Predefined => time.Add(UserSettingsManager.UserSettings.TimeOffset),
TimeOffsetType.UtcToLocalTime => time.ToLocalTime(),
TimeOffsetType.LocalTimeToUtc => time.ToUniversalTime(),
_ => time
};
19
View Source File : CookieCollection.cs
License : MIT License
Project Creator : andruzzzhka
License : MIT License
Project Creator : andruzzzhka
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 = urlDecode (pair.GetValue ('='), Encoding.UTF8);
}
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
View Source File : UnixEpoch.cs
License : MIT License
Project Creator : angusmillar
License : MIT License
Project Creator : angusmillar
public static DateTime UnixTimeStampToLocalDateTime(double unixTimeStamp)
{
// Unix time stamp is seconds past epoch
return Value.AddSeconds(unixTimeStamp).ToLocalTime();
}
19
View Source File : AnimeScraperService.cs
License : GNU General Public License v3.0
Project Creator : AniAPI-Team
License : GNU General Public License v3.0
Project Creator : AniAPI-Team
public override async Task Work()
{
await base.Work();
try
{
foreach (string formatFilter in this._formatsFilter)
{
this._anilistQuery.Variables["format"] = formatFilter;
for (int currentPage = 1; currentPage <= this._totalPages; currentPage++)
{
this._anilistQuery.Variables["page"] = currentPage;
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
Content = new StringContent(JsonConvert.SerializeObject(this._anilistQuery), Encoding.UTF8, "application/json")
};
try
{
using (var response = await this._anilistClient.SendAsync(request))
{
try
{
response.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
if (response.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
{
this._rateLimitReset = Convert.ToInt64(((string[])response.Headers.GetValues("X-RateLimit-Reset"))[0]);
}
throw new HttpRequestException("RateLimit superato", ex);
}
AnilistResponse anilistResponse = JsonConvert.DeserializeObject<AnilistResponse>(await response.Content.ReadreplacedtringAsync());
if (currentPage == 1)
{
this._totalPages = anilistResponse.Data.Page.PageInfo.LastPage;
}
foreach (AnilistResponse.ResponseMedia m in anilistResponse.Data.Page.Media)
{
Anime anime = new Anime(m);
if (this._animeCollection.Exists(ref anime))
{
this._animeCollection.Edit(ref anime);
}
else
{
this._animeCollection.Add(ref anime);
}
}
this._rateLimitRemaining = Convert.ToInt32(((string[])response.Headers.GetValues("X-RateLimit-Remaining"))[0]);
this.Log($"Format {formatFilter} done {GetProgress(currentPage, this._totalPages)}%", true);
}
}
catch (HttpRequestException ex)
{
currentPage--;
DateTime timeOfReset = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
timeOfReset = timeOfReset.AddSeconds(this._rateLimitReset).ToLocalTime();
TimeSpan timeToWait = timeOfReset - DateTime.Now;
this.Log($"Waiting {timeToWait.TotalMilliseconds.ToString("F0")} ms!", true);
Thread.Sleep((int)timeToWait.TotalMilliseconds + 1000);
}
if (_cancellationToken.IsCancellationRequested)
{
throw new TaskCanceledException("Process cancellation requested!");
}
}
}
}
catch(Exception ex)
{
throw;
}
}
19
View Source File : DateHelper.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
public static DateTime StampToDateTime(string time)
{
time = time.Substring(0, 10);
double timestamp = Convert.ToInt64(time);
System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
dateTime = dateTime.AddSeconds(timestamp).ToLocalTime();
return dateTime;
}
19
View Source File : JobTimeRange.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
public override string ToString()
{
return String.Format(
"JobTimeRange: {0:o}-{1:o} {2:o}-{3:o}",
this.From,
this.To,
this.From.ToLocalTime(),
this.To.ToLocalTime());
}
19
View Source File : Shared.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
internal
static Int32 DateTimeToPacked(DateTime time)
{
// The time is preplaceded in here only for purposes of writing LastModified to the
// zip archive. It should always be LocalTime, but we convert anyway. And,
// since the time is being written out, it needs to be adjusted.
time = time.ToLocalTime();
// workitem 7966
//time = AdjustTime_Forward(time);
// see http://www.vsft.com/hal/dostime.htm for the format
UInt16 packedDate = (UInt16)((time.Day & 0x0000001F) | ((time.Month << 5) & 0x000001E0) | (((time.Year - 1980) << 9) & 0x0000FE00));
UInt16 packedTime = (UInt16)((time.Second / 2 & 0x0000001F) | ((time.Minute << 5) & 0x000007E0) | ((time.Hour << 11) & 0x0000F800));
Int32 result = (Int32)(((UInt32)(packedDate << 16)) | packedTime);
return result;
}
19
View Source File : DateTimeExtensions.cs
License : Apache License 2.0
Project Creator : arbing
License : Apache License 2.0
Project Creator : arbing
public static DateTime FromUnixTime(this int unixTime)
{
return BaseTime.AddTicks(unixTime * 10000000L).ToLocalTime();
}
19
View Source File : TimestampConverter.cs
License : MIT License
Project Creator : Archomeda
License : MIT License
Project Creator : Archomeda
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
int timestamp = serializer.Deserialize<int>(reader);
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timestamp).ToLocalTime();
}
19
View Source File : BeatSaver.cs
License : MIT License
Project Creator : Assistant
License : MIT License
Project Creator : Assistant
private static async Task<BeatSaverApiResponse> GetResponse(string url, bool showNotification = true, int retries = 3)
{
if (retries == 0)
{
Modreplacedistant.Utils.Log($"Max tries reached: Skipping {url}", "ERROR");
Utils.SetMessage($"{string.Format((string)Application.Current.FindResource("OneClick:RatelimitSkip"), url)}");
App.CloseWindowOnFinish = false;
throw new Exception("Max retries allowed");
}
BeatSaverApiResponse response = new BeatSaverApiResponse();
try
{
var resp = await HttpClient.GetAsync(url);
response.statusCode = resp.StatusCode;
response.ratelimit = GetRatelimit(resp.Headers);
string body = await resp.Content.ReadreplacedtringAsync();
if ((int)resp.StatusCode == 429)
{
Utils.SetMessage($"{string.Format((string)Application.Current.FindResource("OneClick:RatelimitHit"), response.ratelimit.ResetTime.ToLocalTime())}");
await response.ratelimit.Wait();
return await GetResponse(url, showNotification, retries - 1);
}
if (response.statusCode == HttpStatusCode.OK)
{
response.map = JsonSerializer.Deserialize<BeatSaverApiResponseMap>(body);
return response;
}
else
{
Utils.SetMessage($"{string.Format((string)Application.Current.FindResource("OneClick:Failed"), url)}");
App.CloseWindowOnFinish = false;
return response;
}
}
catch (Exception e)
{
if (showNotification)
{
MessageBox.Show($"{Application.Current.FindResource("OneClick:MapDownloadFailed")}\n\n" + e);
}
return null;
}
}
19
View Source File : BeatSaver.cs
License : MIT License
Project Creator : Assistant
License : MIT License
Project Creator : Assistant
public static async Task Download(string url, string output, int retries = 3)
{
if (retries == 0)
{
Utils.SetMessage($"{string.Format((string)Application.Current.FindResource("OneClick:RatelimitSkip"), url)}");
App.CloseWindowOnFinish = false;
Modreplacedistant.Utils.Log($"Max tries reached: Couldn't download {url}", "ERROR");
throw new Exception("Max retries allowed");
}
var resp = await HttpClient.GetAsync(url);
if ((int)resp.StatusCode == 429)
{
var ratelimit = GetRatelimit(resp.Headers);
Utils.SetMessage($"{string.Format((string)Application.Current.FindResource("OneClick:RatelimitHit"), ratelimit.ResetTime.ToLocalTime())}");
await ratelimit.Wait();
await Download(url, output, retries - 1);
}
using (var stream = await resp.Content.ReadreplacedtreamAsync())
using (var fs = new FileStream(output, FileMode.OpenOrCreate, FileAccess.Write))
{
await stream.CopyToAsync(fs);
}
}
19
View Source File : DateTimeToBsonSerializer.cs
License : GNU General Public License v3.0
Project Creator : atomex-me
License : GNU General Public License v3.0
Project Creator : atomex-me
public override BsonValue Serialize(DateTime dateTime)
{
return dateTime.ToLocalTime();
}
19
View Source File : DateTimeExtensions.cs
License : Microsoft Public License
Project Creator : atrenton
License : Microsoft Public License
Project Creator : atrenton
internal static string Format(this DateTime dt, PagereplacedleEnum pagereplacedle)
{
var dtLocal = dt.ToLocalTime();
var result = dtLocal.ToString(pagereplacedle.XmlEnumValue());
switch (pagereplacedle)
{
case PagereplacedleEnum.DayOfMonthDate_DDD_DD:
case PagereplacedleEnum.DayOfMonthDate_DDDD_DD:
case PagereplacedleEnum.DayOfMonthDate_MMMM_DD:
return string.Concat(result, dtLocal.OrdinalDaySuffix());
default:
return result;
}
}
19
View Source File : UtcToHumanizedLocalDateTimeConverter.cs
License : MIT License
Project Creator : awaescher
License : MIT License
Project Creator : awaescher
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var date = DateTime.SpecifyKind(DateTime.Parse(value.ToString()), DateTimeKind.Utc).ToLocalTime();
return Humanizer.HumanizeTimestamp(date);
}
19
View Source File : UtcToLocalDateTimeConverter.cs
License : MIT License
Project Creator : awaescher
License : MIT License
Project Creator : awaescher
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return DateTime.SpecifyKind(DateTime.Parse(value.ToString()), DateTimeKind.Utc).ToLocalTime();
}
19
View Source File : Extention.DateTime.cs
License : MIT License
Project Creator : awesomedotnetcore
License : MIT License
Project Creator : awesomedotnetcore
public static long ToJsTimestamp(this DateTime dateTime)
{
var startTime = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
long result = (dateTime.Ticks - startTime.Ticks) / 10000; //除10000调整为13位
return result;
}
19
View Source File : Extention.DateTime.cs
License : MIT License
Project Creator : awesomedotnetcore
License : MIT License
Project Creator : awesomedotnetcore
public static int ToUnixTimeStamp(this DateTime time)
{
DateTime startTime = new DateTime(1970, 1, 1).ToLocalTime();
return (int)(time - startTime).TotalSeconds;
}
19
View Source File : Extention.Int.cs
License : MIT License
Project Creator : awesomedotnetcore
License : MIT License
Project Creator : awesomedotnetcore
public static DateTime ToDateTime_From_JsGetTime(this long jsGetTime)
{
DateTime dtStart = new DateTime(1970, 1, 1).ToLocalTime();
long lTime = long.Parse(jsGetTime + "0000"); //说明下,时间格式为13位后面补加4个"0",如果时间格式为10位则后面补加7个"0",至于为什么我也不太清楚,也是仿照人家写的代码转换的
TimeSpan toNow = new TimeSpan(lTime);
DateTime dtResult = dtStart.Add(toNow); //得到转换后的时间
return dtResult;
}
19
View Source File : ExchangeLogParserTest.cs
License : Apache License 2.0
Project Creator : awslabs
License : Apache License 2.0
Project Creator : awslabs
private static async Task TestExchangeLogParser(DelimitedTextLogContext context)
{
var output = new List<IEnvelope<KeyValueLogRecord>>();
var parser = new AsyncExchangeLogParser(NullLogger.Instance, null, null, 1024);
await parser.ParseRecordsAsync(context, output, 10);
replacedert.Equal(2, output.Count);
var record = output[0].Data;
replacedert.Equal("2017-05-22T17:33:35.632Z", record["date-time"]);
replacedert.Equal(new DateTime(2017, 5, 22, 17, 33, 35, 632, DateTimeKind.Utc).ToLocalTime(), record.Timestamp);
replacedert.Equal(string.Empty, record["client-ip"]);
replacedert.Equal("EX13D13UWA001", record["client-hostname"]);
replacedert.Equal("S:AMA=SUM|action=p|error=|atch=0;S:CompCost=|ETR=0;S:DeliveryPriority=Normal;S:[email protected];S:AccountForest=ant.amazon.com", record["custom-data"]);
replacedert.Equal("S:DeliveryPriority=Normal;S:[email protected];S:AccountForest=ant.amazon.com", output[1].Data["custom-data"]);
var envelope = (ILogEnvelope)output[0];
replacedert.Equal(6, envelope.LineNumber);
}
19
View Source File : UniformServerTime.cs
License : Apache License 2.0
Project Creator : awslabs
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;
}
19
View Source File : ZipExtraData.cs
License : MIT License
Project Creator : ay2015
License : MIT License
Project Creator : ay2015
public void SetData(byte[] data, int index, int count)
{
using (MemoryStream ms = new MemoryStream(data, index, count, false))
using (ZipHelperStream helperStream = new ZipHelperStream(ms))
{
// bit 0 if set, modification time is present
// bit 1 if set, access time is present
// bit 2 if set, creation time is present
_flags = (Flags)helperStream.ReadByte();
if (((_flags & Flags.ModificationTime) != 0) && (count >= 5))
{
int iTime = helperStream.ReadLEInt();
_modificationTime = (new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() +
new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime();
}
if ((_flags & Flags.AccessTime) != 0)
{
int iTime = helperStream.ReadLEInt();
_lastAccessTime = (new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() +
new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime();
}
if ((_flags & Flags.CreateTime) != 0)
{
int iTime = helperStream.ReadLEInt();
_createTime = (new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() +
new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime();
}
}
}
See More Examples