System.DateTime.ToUniversalTime()

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

3688 Examples 7

19 Source : IsoDateTimeConverter.cs
with MIT License
from akaskela

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            string text;

            if (value is DateTime)
            {
                DateTime dateTime = (DateTime)value;

                if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
                    || (_dateTimeStyles & DateTimeStyles.replacedumeUniversal) == DateTimeStyles.replacedumeUniversal)
                {
                    dateTime = dateTime.ToUniversalTime();
                }

                text = dateTime.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
            }
#if !NET20
            else if (value is DateTimeOffset)
            {
                DateTimeOffset dateTimeOffset = (DateTimeOffset)value;
                if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
                    || (_dateTimeStyles & DateTimeStyles.replacedumeUniversal) == DateTimeStyles.replacedumeUniversal)
                {
                    dateTimeOffset = dateTimeOffset.ToUniversalTime();
                }

                text = dateTimeOffset.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
            }
#endif
            else
            {
                throw new JsonSerializationException("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value)));
            }

            writer.WriteValue(text);
        }

19 Source : AuditGetRecentUpdates.cs
with MIT License
from akaskela

protected DataTable BuildDataTable(CodeActivityContext context, IWorkflowContext workflowContext, IOrganizationService service)
        {
            TimeZoneSummary timeZone = StaticMethods.CalculateTimeZoneToUse(this.TimeZoneOption.Get(context), workflowContext, service);
            
            DataTable table = new DataTable() { TableName = workflowContext.PrimaryEnreplacedyName };
            table.Columns.AddRange(new DataColumn[] { new DataColumn("Date"), new DataColumn("User"), new DataColumn("Attribute"), new DataColumn("Old Value"), new DataColumn("New Value") });
            DateTime oldestUpdate = DateTime.MinValue;

            if (this.Units != null && this.Number != null && this.Number.Get<int>(context) != 0)
            {
                OptionSetValue value = this.Units.Get<OptionSetValue>(context);
                if (value != null)
                {
                    switch (value.Value)
                    {
                        case 222540000:
                            oldestUpdate = DateTime.Now.AddYears(this.Number.Get<int>(context) * -1);
                            break;
                        case 222540001:
                            oldestUpdate = DateTime.Now.AddMonths(this.Number.Get<int>(context) * -1);
                            break;
                        case 222540002:
                            oldestUpdate = DateTime.Now.AddDays(this.Number.Get<int>(context) * -7);
                            break;
                        case 222540003:
                            oldestUpdate = DateTime.Now.AddDays(this.Number.Get<int>(context) * -1);
                            break;
                        case 222540004:
                            oldestUpdate = DateTime.Now.AddHours(this.Number.Get<int>(context) * -1);
                            break;
                        default:
                            oldestUpdate = DateTime.Now.AddMinutes(this.Number.Get<int>(context) * -1);
                            break;
                    }
                }
            }

            int maxUpdates = this.MaxAuditLogs.Get(context) > 100 || this.MaxAuditLogs.Get(context) < 1 ? 100 : this.MaxAuditLogs.Get(context);
            RetrieveRecordChangeHistoryRequest request = new RetrieveRecordChangeHistoryRequest()
            {
                Target = new EnreplacedyReference(workflowContext.PrimaryEnreplacedyName, workflowContext.PrimaryEnreplacedyId),
                PagingInfo = new PagingInfo() { Count = maxUpdates, PageNumber = 1 }
            };
            RetrieveRecordChangeHistoryResponse response = service.Execute(request) as RetrieveRecordChangeHistoryResponse;
            var detailsToInclude = response.AuditDetailCollection.AuditDetails
                .Where(ad => ad is AttributeAuditDetail && ad.AuditRecord.Contains("createdon") && ((DateTime)ad.AuditRecord["createdon"]) > oldestUpdate)
                .OrderByDescending(ad => ((DateTime)ad.AuditRecord["createdon"]))
                .ToList();

            if (detailsToInclude.Any())
            {
                Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyRequest retrieveEnreplacedyRequest = new Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyRequest()
                {
                    EnreplacedyFilters = EnreplacedyFilters.Attributes,
                    LogicalName = workflowContext.PrimaryEnreplacedyName
                };
                Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyResponse retrieveEnreplacedyResponse = service.Execute(retrieveEnreplacedyRequest) as Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyResponse;
                EnreplacedyMetadata metadata = retrieveEnreplacedyResponse.EnreplacedyMetadata;

                foreach (var detail in detailsToInclude.Select(d => d as AttributeAuditDetail).Where(d => d.NewValue != null && d.OldValue != null))
                {
                    DateTime dateToModify = (DateTime)detail.AuditRecord["createdon"];
                    if (dateToModify.Kind != DateTimeKind.Utc)
                    {
                        dateToModify = dateToModify.ToUniversalTime();
                    }


                    LocalTimeFromUtcTimeRequest timeZoneChangeRequest = new LocalTimeFromUtcTimeRequest() { UtcTime = dateToModify, TimeZoneCode = timeZone.MicrosoftIndex };
                    LocalTimeFromUtcTimeResponse timeZoneResponse = service.Execute(timeZoneChangeRequest) as LocalTimeFromUtcTimeResponse;
                    DateTime timeZoneSpecificDateTime = timeZoneResponse.LocalTime;

                    var details = detail.NewValue.Attributes.Keys.Union(detail.OldValue.Attributes.Keys)
                        .Distinct()
                        .Select(a =>
                        new {
                            AttributeName = a,
                            DisplayName = GetDisplayLabel(metadata, a)
                        })
                        .OrderBy(a => a.DisplayName);

                    foreach (var item in details)
                    {
                        DataRow newRow = table.NewRow();
                        newRow["User"] = GetDisplayValue(detail.AuditRecord, "userid");
                        newRow["Date"] = timeZoneSpecificDateTime.ToString("MM/dd/yyyy h:mm tt");
                        newRow["Attribute"] = item.DisplayName;
                        newRow["Old Value"] = GetDisplayValue(detail.OldValue, item.AttributeName);
                        newRow["New Value"] = GetDisplayValue(detail.NewValue, item.AttributeName);
                        table.Rows.Add(newRow);
                    }
                }
            }
            return table;
        }

19 Source : BsonBinaryWriter.cs
with MIT License
from 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 Source : JavaScriptDateTimeConverter.cs
with MIT License
from akaskela

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            long ticks;

            if (value is DateTime)
            {
                DateTime dateTime = (DateTime)value;
                DateTime utcDateTime = dateTime.ToUniversalTime();
                ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(utcDateTime);
            }
#if !NET20
            else if (value is DateTimeOffset)
            {
                DateTimeOffset dateTimeOffset = (DateTimeOffset)value;
                DateTimeOffset utcDateTimeOffset = dateTimeOffset.ToUniversalTime();
                ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(utcDateTimeOffset.UtcDateTime);
            }
#endif
            else
            {
                throw new JsonSerializationException("Expected date object value.");
            }

            writer.WriteStartConstructor("Date");
            writer.WriteValue(ticks);
            writer.WriteEndConstructor();
        }

19 Source : DateTimeUtils.cs
with MIT License
from akaskela

private static DateTime SwitchToUtcTime(DateTime value)
        {
            switch (value.Kind)
            {
                case DateTimeKind.Unspecified:
                    return new DateTime(value.Ticks, DateTimeKind.Utc);

                case DateTimeKind.Utc:
                    return value;

                case DateTimeKind.Local:
                    return value.ToUniversalTime();
            }
            return value;
        }

19 Source : DateConvertToCustomText.cs
with MIT License
from akaskela

protected override void Execute(CodeActivityContext context)
        {
            var workflowContext = context.GetExtension<IWorkflowContext>();
            var service = this.RetrieveOrganizationService(context);

            List<OptionSetValue> values = new List<OptionSetValue>()  {
                this.Part1.Get<OptionSetValue>(context),
                this.Part2.Get<OptionSetValue>(context),
                this.Part3.Get<OptionSetValue>(context),
                this.Part4.Get<OptionSetValue>(context),
                this.Part5.Get<OptionSetValue>(context),
                this.Part6.Get<OptionSetValue>(context),
                this.Part7.Get<OptionSetValue>(context),
                this.Part8.Get<OptionSetValue>(context),
                this.Part9.Get<OptionSetValue>(context),
                this.Part10.Get<OptionSetValue>(context),
                this.Part11.Get<OptionSetValue>(context),
                this.Part12.Get<OptionSetValue>(context),
                this.Part13.Get<OptionSetValue>(context),
                this.Part14.Get<OptionSetValue>(context),
                this.Part15.Get<OptionSetValue>(context),
                this.Part16.Get<OptionSetValue>(context),
                this.Part17.Get<OptionSetValue>(context),
                this.Part18.Get<OptionSetValue>(context),
                this.Part19.Get<OptionSetValue>(context),
                this.Part20.Get<OptionSetValue>(context) };
            values.RemoveAll(osv => osv == null || osv.Value == 222540025);

            TimeZoneSummary timeZone = StaticMethods.CalculateTimeZoneToUse(this.TimeZoneOption.Get(context), workflowContext, service);
            DateTime dateToModify = this.DateToModify.Get(context);

            if (dateToModify.Kind != DateTimeKind.Utc)
            {
                dateToModify = dateToModify.ToUniversalTime();
            }

            
            LocalTimeFromUtcTimeRequest timeZoneChangeRequest = new LocalTimeFromUtcTimeRequest() { UtcTime = dateToModify, TimeZoneCode = timeZone.MicrosoftIndex };
            LocalTimeFromUtcTimeResponse timeZoneResponse = service.Execute(timeZoneChangeRequest) as LocalTimeFromUtcTimeResponse;
            DateTime timeZoneSpecificDateTime = timeZoneResponse.LocalTime;
            
            StringBuilder sb = new StringBuilder();
            
            foreach (OptionSetValue osv in values)
            {
                try
                {
                    switch (osv.Value)
                    {
                        case 222540000:
                            sb.Append(timeZoneSpecificDateTime.ToString("%h"));
                            break;
                        case 222540001:
                            sb.Append(timeZoneSpecificDateTime.ToString("hh"));
                            break;
                        case 222540002:
                            sb.Append(timeZoneSpecificDateTime.ToString("%H"));
                            break;
                        case 222540003:
                            sb.Append(timeZoneSpecificDateTime.ToString("HH"));
                            break;
                        case 222540004:
                            sb.Append(timeZoneSpecificDateTime.ToString("%m"));
                            break;
                        case 222540005:
                            sb.Append(timeZoneSpecificDateTime.ToString("mm"));
                            break;
                        case 222540006:
                            sb.Append(timeZoneSpecificDateTime.ToString("%d"));
                            break;
                        case 222540007:
                            sb.Append(timeZoneSpecificDateTime.ToString("dd"));
                            break;
                        case 222540008:
                            sb.Append(timeZoneSpecificDateTime.ToString("ddd"));
                            break;
                        case 222540009:
                            sb.Append(timeZoneSpecificDateTime.ToString("dddd"));
                            break;
                        case 222540010:
                            sb.Append(timeZoneSpecificDateTime.ToString("%M"));
                            break;
                        case 222540011:
                            sb.Append(timeZoneSpecificDateTime.ToString("MM"));
                            break;
                        case 222540012:
                            sb.Append(timeZoneSpecificDateTime.ToString("MMM"));
                            break;
                        case 222540013:
                            sb.Append(timeZoneSpecificDateTime.ToString("MMMM"));
                            break;
                        case 222540014:
                            sb.Append(timeZoneSpecificDateTime.ToString("%y"));
                            break;
                        case 222540015:
                            sb.Append(timeZoneSpecificDateTime.ToString("yy"));
                            break;
                        case 222540016:
                            sb.Append(timeZoneSpecificDateTime.ToString("yyyy"));
                            break;
                        case 222540017:
                            sb.Append(timeZoneSpecificDateTime.ToString("%t"));
                            break;
                        case 222540018:
                            sb.Append(timeZoneSpecificDateTime.ToString("tt"));
                            break;
                        case 222540019:
                            sb.Append(" ");
                            break;
                        case 222540020:
                            sb.Append(",");
                            break;
                        case 222540021:
                            sb.Append(".");
                            break;
                        case 222540022:
                            sb.Append(":");
                            break;
                        case 222540023:
                            sb.Append("/");
                            break;
                        case 222540024:
                            sb.Append(@"\");
                            break;
                        case 222540026:
                            sb.Append("-");
                            break;
                        case 222540027:
                            sb.Append(timeZone.Id);
                            break;
                        case 222540028:
                            sb.Append(timeZone.FullName);
                            break;
                        default:
                            break;
                    }
                }
                catch
                {
                    throw new Exception(osv.Value.ToString());
                }
            }
            
            FormattedDate.Set(context, sb.ToString());
        }

19 Source : JsonSerializer.cs
with MIT License
from AlenToma

private void WriteDateTime(DateTime dateTime)
        {
            // datetime format standard : yyyy-MM-dd HH:mm:ss
            DateTime dt = dateTime;
            if (_params.UseUTCDateTime)
                dt = dateTime.ToUniversalTime();

            write_date_value(dt);

            if (_params.DateTimeMilliseconds)
            {
                _output.Append('.');
                _output.Append(dt.Millisecond.ToString("000", NumberFormatInfo.InvariantInfo));
            }

            if (_params.UseUTCDateTime)
                _output.Append('Z');

            _output.Append('\"');
        }

19 Source : RrSigRecord.cs
with Apache License 2.0
from alexreinert

internal override string RecordDataToString()
		{
			return TypeCovered.ToShortString()
			       + " " + (byte) Algorithm
			       + " " + Labels
			       + " " + OriginalTimeToLive
			       + " " + SignatureExpiration.ToUniversalTime().ToString("yyyyMMddHHmmss")
			       + " " + SignatureInception.ToUniversalTime().ToString("yyyyMMddHHmmss")
			       + " " + KeyTag
			       + " " + SignersName
			       + " " + Signature.ToBase64String();
		}

19 Source : SigRecord.cs
with Apache License 2.0
from alexreinert

internal static void EncodeDateTime(byte[] buffer, ref int currentPosition, DateTime value)
		{
			int timeStamp = (int) (value.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
			DnsMessageBase.EncodeInt(buffer, ref currentPosition, timeStamp);
		}

19 Source : TSigRecord.cs
with Apache License 2.0
from alexreinert

internal static void EncodeDateTime(byte[] buffer, ref int currentPosition, DateTime value)
		{
			long timeStamp = (long) (value.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;

			if (BitConverter.IsLittleEndian)
			{
				buffer[currentPosition++] = (byte) ((timeStamp >> 40) & 0xff);
				buffer[currentPosition++] = (byte) ((timeStamp >> 32) & 0xff);
				buffer[currentPosition++] = (byte) (timeStamp >> 24 & 0xff);
				buffer[currentPosition++] = (byte) ((timeStamp >> 16) & 0xff);
				buffer[currentPosition++] = (byte) ((timeStamp >> 8) & 0xff);
				buffer[currentPosition++] = (byte) (timeStamp & 0xff);
			}
			else
			{
				buffer[currentPosition++] = (byte) (timeStamp & 0xff);
				buffer[currentPosition++] = (byte) ((timeStamp >> 8) & 0xff);
				buffer[currentPosition++] = (byte) ((timeStamp >> 16) & 0xff);
				buffer[currentPosition++] = (byte) ((timeStamp >> 24) & 0xff);
				buffer[currentPosition++] = (byte) ((timeStamp >> 32) & 0xff);
				buffer[currentPosition++] = (byte) ((timeStamp >> 40) & 0xff);
			}
		}

19 Source : RequestAuthenticator.cs
with Apache License 2.0
from AlexWan

private static long UnixTimeStampUtc()
        {
            int unixTimeStamp;
            var currentTime = DateTime.Now;
            var dt = currentTime.ToUniversalTime();
            var unixEpoch = new DateTime(1970, 1, 1);
            unixTimeStamp = (Int32)(dt.Subtract(unixEpoch)).TotalSeconds;
            return unixTimeStamp;
        }

19 Source : ServerWebhook.cs
with Apache License 2.0
from AlexWan

private string WebUtcTime(DateTime time)
        {
            return time.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
        }

19 Source : ServerWebhook.cs
with Apache License 2.0
from AlexWan

private string UnixEpochTimestamp(DateTime time)
        {
            return (time.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalSeconds.ToString();
        }

19 Source : FTXTradesCreator.cs
with Apache License 2.0
from AlexWan

public List<Trade> Create (JToken data, string securityName, bool isUtcTime = false)
        {
            var trades = new List<Trade>();
            var jProperties = data.Children();

            foreach (var jProperty in jProperties)
            {
                var trade = new Trade();

                DateTime time = jProperty.SelectToken(TimePath).Value<DateTime>();
                if (isUtcTime)
                {
                    time = time.ToUniversalTime();
                }

                trade.Time = time;
                trade.SecurityNameCode = securityName;
                trade.Price = jProperty.SelectToken(PricePath).Value<decimal>();
                trade.Id = jProperty.SelectToken(IdPath).ToString();
                trade.Side = jProperty.SelectToken(SidePath).ToString() == "sell" ? Side.Sell : Side.Buy;
                trade.Volume = jProperty.SelectToken(SizePath).Value<decimal>();

                trades.Add(trade);
            }

            return trades;
        }

19 Source : InteractiveBrokersServer.cs
with Apache License 2.0
from AlexWan

public List<Candle> GetCandleHistory(string nameSec, TimeFrame tf)
        {
            SecurityIb contractIb =
_secIB.Find(
contract =>
 contract.Symbol + "_" + contract.SecType + "_" + contract.Exchange == nameSec);

            if (contractIb == null)
            {
                return null; ;
            }

            DateTime timeEnd = DateTime.Now.ToUniversalTime();
            DateTime timeStart = timeEnd.AddMinutes(60);

            string barSize = "1 min";

            int mergeCount = 0;


            if (tf == TimeFrame.Sec1)
            {
                barSize = "1 sec";
                timeStart = timeEnd.AddMinutes(10);
            }
            else if (tf == TimeFrame.Sec5)
            {
                barSize = "5 secs";
            }
            else if (tf == TimeFrame.Sec15)
            {
                barSize = "15 secs";
            }
            else if (tf == TimeFrame.Sec30)
            {
                barSize = "30 secs";
            }
            else if (tf == TimeFrame.Min1)
            {
                timeStart = timeEnd.AddHours(5);
                barSize = "1 min";
            }
            else if (tf == TimeFrame.Min5)
            {
                timeStart = timeEnd.AddHours(25);
                barSize = "5 mins";
            }
            else if (tf == TimeFrame.Min15)
            {
                timeStart = timeEnd.AddHours(75);
                barSize = "15 mins";
            }
            else if (tf == TimeFrame.Min30)
            {
                timeStart = timeEnd.AddHours(150);
                barSize = "30 mins";
            }
            else if (tf == TimeFrame.Hour1)
            {
                timeStart = timeEnd.AddHours(1300);
                barSize = "1 hour";
            }
            else if (tf == TimeFrame.Hour2)
            {
                timeStart = timeEnd.AddHours(2100);
                barSize = "1 hour";
                mergeCount = 2;
            }
            else if (tf == TimeFrame.Hour4)
            {
                timeStart = timeEnd.AddHours(4200);
                barSize = "1 hour";
                mergeCount = 4;
            }
            else if (tf == TimeFrame.Day)
            {
                barSize = "1 day";
                timeStart = timeEnd.AddDays(701);
            }
            else
            {
                return null;
            }

            CandlesRequestResult = null;

            _client.GetCandles(contractIb, timeEnd, timeStart, barSize, "TRADES");

            DateTime startSleep = DateTime.Now;

            while (true)
            {
                Thread.Sleep(1000);

                if (startSleep.AddSeconds(30) < DateTime.Now)
                {
                    break;
                }

                if (CandlesRequestResult != null)
                {
                    break;
                }
            }

            if (CandlesRequestResult != null &&
                CandlesRequestResult.CandlesArray.Count != 0)
            {
                if (mergeCount != 0)
                {
                    List<Candle> newCandles = Merge(CandlesRequestResult.CandlesArray, mergeCount);
                    CandlesRequestResult.CandlesArray = newCandles;
                    return StraichCandles(CandlesRequestResult);
                }

                return StraichCandles(CandlesRequestResult);
            }


            _client.GetCandles(contractIb, timeEnd, timeStart, barSize, "MIDPOINT");

            startSleep = DateTime.Now;

            while (true)
            {
                Thread.Sleep(1000);

                if (startSleep.AddSeconds(30) < DateTime.Now)
                {
                    break;
                }

                if (CandlesRequestResult != null)
                {
                    break;
                }
            }

            if (CandlesRequestResult != null &&
                CandlesRequestResult.CandlesArray.Count != 0)
            {
                if (mergeCount != 0)
                {
                    List<Candle> newCandles = Merge(CandlesRequestResult.CandlesArray, mergeCount);
                    CandlesRequestResult.CandlesArray = newCandles;
                    return StraichCandles(CandlesRequestResult);
                }

                return StraichCandles(CandlesRequestResult);
            }

            return null;
        }

19 Source : RequestBase.cs
with MIT License
from aliyun

protected Dictionary<string, string> BuildCommonHeaders(string method, string path, Dictionary<string, string> customHeaders = null, Dictionary<string, string[]> unescapedQueries = null)
        {
            Dictionary<string, string> headers = new Dictionary<string, string> {
                { "host", this.Config.Host},
                { "date", DateTime.Now.ToUniversalTime().ToString("r")},
                { "content-type", "application/json"},
                { "content-length", "0"},
                { "user-agent", this.Config.UserAgent},
            };

            if (this.Config.SecurityToken != "")
                headers.Add("x-fc-security-token", this.Config.SecurityToken);

            if (customHeaders != null)
                headers = Helper.MergeDictionary(headers, customHeaders);

            headers.Add("authorization", Auth.SignRequest(method, path, headers, unescapedQueries));

            return headers;
        }

19 Source : SdkDateTimeDdbConverter.cs
with MIT License
from AllocZero

public override AttributeValue Write(ref DateTime value)
        {
            var utcValue = value.ToUniversalTime();
            return base.Write(ref utcValue);
        }

19 Source : SdkDateTimeDdbConverter.cs
with MIT License
from AllocZero

public override void Write(in DdbWriter writer, ref DateTime value)
        {
            var utcValue = value.ToUniversalTime();
            base.Write(in writer, ref utcValue);
        }

19 Source : SdkDateTimeDdbConverter.cs
with MIT License
from AllocZero

public override void WritePropertyName(in DdbWriter writer, ref DateTime value)
        {
            var utcValue = value.ToUniversalTime();
            base.WritePropertyName(in writer, ref utcValue);
        }

19 Source : SdkDateTimeDdbConverter.cs
with MIT License
from AllocZero

public override string WriteStringValue(ref DateTime value)
        {
            var utcValue = value.ToUniversalTime();
            return base.WriteStringValue(ref utcValue);
        }

19 Source : SdkDateTimeDdbConverter.cs
with MIT License
from AllocZero

public override void WriteStringValue(in DdbWriter writer, ref DateTime value)
        {
            var utcValue = value.ToUniversalTime();
            base.WriteStringValue(in writer, ref utcValue);
        }

19 Source : DateTime2ndExtension.cs
with MIT License
from AlphaYu

public static TimeSpan ToEpochTimeSpan(this DateTime @this) => @this.ToUniversalTime().Subtract(new DateTime(1970, 1, 1));

19 Source : PolicyRepositoryMock.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

private async Task<Response<BlobContentInfo>> WriteStreamToTestDataFolder(string filepath, Stream fileStream)
        {
            string dataPath = GetDataBlobPath() + filepath;

            if (!Directory.Exists(Path.GetDirectoryName(dataPath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(dataPath));
            }

            int filesize;

            using (Stream streamToWriteTo = File.Open(dataPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                await fileStream.CopyToAsync(streamToWriteTo);
                streamToWriteTo.Flush();
                filesize = (int)streamToWriteTo.Length;
            }

            BlobContentInfo mockedBlobInfo = BlobsModelFactory.BlobContentInfo(new ETag("ETagSuccess"), DateTime.Now, new byte[1], DateTime.Now.ToUniversalTime().ToString(), "encryptionKeySha256", "encryptionScope", 1);
            Mock<Response<BlobContentInfo>> mockResponse = new Mock<Response<BlobContentInfo>>();
            mockResponse.SetupGet(r => r.Value).Returns(mockedBlobInfo);

            Mock<Response> responseMock = new Mock<Response>();
            responseMock.SetupGet(r => r.Status).Returns((int)HttpStatusCode.Created);
            mockResponse.Setup(r => r.GetRawResponse()).Returns(responseMock.Object);

            return mockResponse.Object;
        }

19 Source : DateTimeHelper.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

public static DateTime? ConvertToUniversalTime(DateTime? date)
        {
            if (date.HasValue)
            {
                DateTime timestamp = date.Value;

                if (timestamp.Kind == DateTimeKind.Utc)
                {
                    return timestamp;
                }
                else if (timestamp.Kind == DateTimeKind.Local)
                {
                    return timestamp.ToUniversalTime();
                }
                else if (timestamp.Kind == DateTimeKind.Unspecified)
                {
                    // force unspecified timezone to be interpreted as UTC
                    string unspecifiedTimezoneDateTime = timestamp.ToString(Iso8601Format, CultureInfo.InvariantCulture);
                    DateTime utc = DateTime.ParseExact(unspecifiedTimezoneDateTime + "Z", Iso8601UtcFormat, CultureInfo.InvariantCulture);
                    return utc.ToUniversalTime();
                }
            }

            return null;
        }

19 Source : Utils.cs
with MIT License
from 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 Source : DataBuffer.cs
with MIT License
from AndreasAmMueller

public void SetDateTime(int index, DateTime value, bool localTime = false)
		{
			var dt = localTime ? value.ToUniversalTime() : value;
			var ts = dt.Subtract(unixEpoch);
			SetTimeSpan(index, ts);
		}

19 Source : DataBuffer.cs
with MIT License
from AndreasAmMueller

public void AddDateTime(DateTime value)
		{
			var dt = value.Kind switch
			{
				DateTimeKind.Utc => value,
				DateTimeKind.Local => value.ToUniversalTime(),
				_ => DateTime.SpecifyKind(value, DateTimeKind.Utc)
			};

19 Source : Cookie.cs
with MIT License
from andruzzzhka

private string toResponseStringVersion0 ()
    {
      var output = new StringBuilder (64);
      output.AppendFormat ("{0}={1}", _name, _value);

      if (_expires != DateTime.MinValue)
        output.AppendFormat (
          "; Expires={0}",
          _expires.ToUniversalTime ().ToString (
            "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'",
            CultureInfo.CreateSpecificCulture ("en-US")));

      if (!_path.IsNullOrEmpty ())
        output.AppendFormat ("; Path={0}", _path);

      if (!_domain.IsNullOrEmpty ())
        output.AppendFormat ("; Domain={0}", _domain);

      if (_secure)
        output.Append ("; Secure");

      if (_httpOnly)
        output.Append ("; HttpOnly");

      return output.ToString ();
    }

19 Source : JwtFactory.cs
with MIT License
from Andyhacool

private static long ToUnixEpochDate(DateTime date)
          => (long)Math.Round((date.ToUniversalTime() -
                               new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero))
                              .TotalSeconds);

19 Source : Engine.cs
with GNU Affero General Public License v3.0
from ankenyr

public static double ConvertToUnixTimestamp(DateTime date)
        {
            DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            TimeSpan diff = date.ToUniversalTime() - origin;
            return Math.Floor(diff.TotalSeconds);
        }

19 Source : DateFormats.cs
with MIT License
from anthonyreilly

public static string FullDateString(DateTime dt)
        {
            return dt.ToUniversalTime().ToString(_FullFormat);
        }

19 Source : SalesforceVisitor.cs
with MIT License
from anthonyreilly

protected override Expression VisitConstant(ConstantExpression c)
        {
            switch (c.Value)
            {
                case IQueryable queryable:
                    ElementType = queryable.ElementType;
                    return c;

                case IAsyncQueryable asyncQueryable:
                    ElementType = asyncQueryable.ElementType;
                    return c;

                case string str:

                    var escapedString = str
                                .Replace("\\", "\\\\")
                                .Replace("\"", "\\\"")
                                .Replace("'", "\\\'");

                    return Expression.Constant($"'{escapedString}'");

                case bool boolean:
                    return Expression.Constant(boolean ? "TRUE" : "FALSE");

                case null:
                    return Expression.Constant("NULL");
                
                case SalesforceDate date:
                    return Expression.Constant(date.ToString());
            }


            switch (c.Value)
            {
                case string str:
                    return Expression.Constant(string.Format("'{0}'", str));

                case DateTime dateTime:
                    return Expression.Constant(dateTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.ffffZ"));

                case DateTimeOffset dateTimeOffset:
                    return Expression.Constant(dateTimeOffset.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.ffffZ"));

                case CancellationToken ct:
                    //Ignore
                    return null;
                case object o:
                    throw new NotSupportedException($"The constant for '{o}' ({o.GetType().Name}) is not supported");

                default:
                    return Expression.Constant(c.Value.ToString());
            }
        }

19 Source : DateTimeService.cs
with MIT License
from AntonyCorbett

public DateTime UtcNow()
        {
            if (_forcedDateTimeAtStart != null)
            {
                return Now().ToUniversalTime();
            }

            return DateTime.UtcNow;
        }

19 Source : MessageDeliveryTimeTest.cs
with Apache License 2.0
from apache

[Test, Timeout(20000)]
        public void TestDeliveryTimeIsDateTime()
        {
            DateTime deliveryTime = DateTimeOffset.FromUnixTimeMilliseconds(CurrentTimeInMillis() + 12345).DateTime.ToUniversalTime();
            DoReceiveMessageDeliveryTime(deliveryTime, deliveryTime);
        }

19 Source : MessageDeliveryTimeTestAsync.cs
with Apache License 2.0
from apache

[Test, Timeout(20000)]
        public async Task TestDeliveryTimeIsDateTime()
        {
            DateTime deliveryTime = DateTimeOffset.FromUnixTimeMilliseconds(CurrentTimeInMillis() + 12345).DateTime.ToUniversalTime();
            await DoReceiveMessageDeliveryTime(deliveryTime, deliveryTime);
        }

19 Source : RelativeTimePatternConverter.cs
with Apache License 2.0
from apache

private static long TimeDifferenceInMillis(DateTime start, DateTime end)
		{
			// We must convert all times to UTC before performing any mathematical
			// operations on them. This allows use to take into account discontinuities
			// caused by daylight savings time transitions.
			return (long)(end.ToUniversalTime() - start.ToUniversalTime()).TotalMilliseconds;
		}

19 Source : XmlLayoutTest.cs
with Apache License 2.0
from apache

private LoggingEventData CreateBaseEvent()
		{
			LoggingEventData ed = new LoggingEventData();
			ed.Domain = "Tests";
			ed.ExceptionString = "";
			ed.Idenreplacedy = "TestRunner";
			ed.Level = Level.Info;
			ed.LocationInfo = new LocationInfo(GetType());
			ed.LoggerName = "TestLogger";
			ed.Message = "Test message";
			ed.ThreadName = "TestThread";
			ed.TimeStampUtc = DateTime.Today.ToUniversalTime();
			ed.UserName = "TestRunner";
			ed.Properties = new PropertiesDictionary();

			return ed;
		}

19 Source : ApexSettings.cs
with GNU Lesser General Public License v3.0
from ApexGameTools

internal void LatestNewsRetrieved(DateTime latestNewsDate)
        {
            if (latestNewsDate.Kind != DateTimeKind.Utc)
            {
                latestNewsDate = latestNewsDate.ToUniversalTime();
            }

            _lastNewsDate = latestNewsDate.ToString(DateTimeFormatInfo.InvariantInfo);
            _isDirty = true;
            SaveChanges();
        }

19 Source : ControllerApi.cs
with Apache License 2.0
from Appdynamics

public string GetListOfSnapshotsFirstPage(long applicationID, DateTime startTime, DateTime endTime, int durationBetweenTimes, int maxRows)
        {
            // Full body of the snapshot re
            //@"{\
            //    ""firstInChain"": true,
            //    ""maxRows"": {4},
            //    ""applicationIds"": [{0}],
            //    ""businessTransactionIds"": [],
            //    ""applicationComponentIds"": [],
            //    ""applicationComponentNodeIds"": [],
            //    ""errorIDs"": [],
            //    ""errorOccured"": null,
            //    ""userExperience"": [],
            //    ""executionTimeInMilis"": null,
            //    ""endToEndLatency"": null,
            //    ""url"": null,
            //    ""sessionId"": null,
            //    ""userPrincipalId"": null,
            //    ""dataCollectorFilter"": null,
            //    ""archived"": null,
            //    ""guids"": [],
            //    ""diagnosticSnapshot"": null,
            //    ""badRequest"": null,
            //    ""deepDivePolicy"": [],
            //    ""rangeSpecifier"": {
            //        ""type"": ""BETWEEN_TIMES"",
            //        ""startTime"": ""{1:o}"",
            //        ""endTime"": ""{2:o}"",
            //        ""durationInMinutes"": {3}
            //    }
            //}";

            string requestJSONTemplate =
@"{{
    ""firstInChain"": true,
    ""maxRows"": {4},
    ""applicationIds"": [{0}],
    ""rangeSpecifier"": {{
        ""type"": ""BETWEEN_TIMES"",
        ""startTime"": ""{1:o}"",
        ""endTime"": ""{2:o}"",
        ""durationInMinutes"": {3}
    }}
}}";

            // The controller expects the data in one of the following forms for java.util.Date:
            // "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
            // "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
            // "EEE, dd MMM yyyy HH:mm:ss zzz", 
            // "yyyy-MM-dd"
            string requestBody = String.Format(requestJSONTemplate,
                applicationID,
                startTime.ToUniversalTime(),
                endTime.ToUniversalTime(),
                durationBetweenTimes,
                maxRows);

            return this.apiPOST("controller/restui/snapshot/snapshotListDataWithFilterHandle", "application/json", requestBody, "application/json", true);
        }

19 Source : ControllerApi.cs
with Apache License 2.0
from Appdynamics

public string GetListOfSnapshotsNextPage_Type_rsdScrollId(long applicationID, DateTime startTime, DateTime endTime, int durationBetweenTimes, int maxRows, long serverCursorId)
        {
            string requestJSONTemplate =
@"{{
    ""firstInChain"": true,
    ""maxRows"": {4},
    ""applicationIds"": [{0}],
    ""rangeSpecifier"": {{
        ""type"": ""BETWEEN_TIMES"",
        ""startTime"": ""{1:o}"",
        ""endTime"": ""{2:o}"",
        ""durationInMinutes"": {3}
    }},
    ""serverCursor"": {{
        ""rsdScrollId"": {5}
    }}
}}";

            // The controller expects the data in one of the following forms for java.util.Date:
            // "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
            // "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
            // "EEE, dd MMM yyyy HH:mm:ss zzz", 
            // "yyyy-MM-dd"
            string requestBody = String.Format(requestJSONTemplate,
                applicationID,
                startTime.ToUniversalTime(),
                endTime.ToUniversalTime(),
                durationBetweenTimes,
                maxRows,
                serverCursorId);

            return this.apiPOST("controller/restui/snapshot/snapshotListDataWithFilterHandle", "application/json", requestBody, "application/json", true);
        }

19 Source : ControllerApi.cs
with Apache License 2.0
from Appdynamics

public string GetListOfSnapshotsNextPage_Type_scrollId(long applicationID, DateTime startTime, DateTime endTime, int durationBetweenTimes, int maxRows, long serverCursorId)
        {
            string requestJSONTemplate =
@"{{
    ""firstInChain"": true,
    ""maxRows"": {4},
    ""applicationIds"": [{0}],
    ""rangeSpecifier"": {{
        ""type"": ""BETWEEN_TIMES"",
        ""startTime"": ""{1:o}"",
        ""endTime"": ""{2:o}"",
        ""durationInMinutes"": {3}
    }},
    ""serverCursor"": {{
        ""scrollId"": {5}
    }}
}}";

            // The controller expects the data in one of the following forms for java.util.Date:
            // "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
            // "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
            // "EEE, dd MMM yyyy HH:mm:ss zzz", 
            // "yyyy-MM-dd"
            string requestBody = String.Format(requestJSONTemplate,
                applicationID,
                startTime.ToUniversalTime(),
                endTime.ToUniversalTime(),
                durationBetweenTimes,
                maxRows,
                serverCursorId);

            return this.apiPOST("controller/restui/snapshot/snapshotListDataWithFilterHandle", "application/json", requestBody, "application/json", true);
        }

19 Source : ControllerApi.cs
with Apache License 2.0
from Appdynamics

public string GetListOfSnapshotsNextPage_Type_handle(long applicationID, DateTime startTime, DateTime endTime, int durationBetweenTimes, int maxRows, long serverCursorId)
        {
            // This was build for 4.2.3 and earlier. I can't figure out what endRequestId is supposed to be. So this will only ever retrieve maxRows rows max
            string requestJSONTemplate =
@"{{
    ""firstInChain"": true,
    ""maxRows"": {4},
    ""applicationIds"": [{0}],
    ""rangeSpecifier"": {{
        ""type"": ""BETWEEN_TIMES"",
        ""startTime"": ""{1:o}"",
        ""endTime"": ""{2:o}"",
        ""durationInMinutes"": {3}
    }},
    ""startingRequestId"": 1,
    ""endRequestId"": 1,
    ""handle"": {5}
}}";

            // The controller expects the data in one of the following forms for java.util.Date:
            // "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
            // "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
            // "EEE, dd MMM yyyy HH:mm:ss zzz", 
            // "yyyy-MM-dd"
            string requestBody = String.Format(requestJSONTemplate,
                applicationID,
                startTime.ToUniversalTime(),
                endTime.ToUniversalTime(),
                durationBetweenTimes,
                maxRows,
                serverCursorId);

            return this.apiPOST("controller/restui/snapshot/snapshotListDataWithFilterHandle", "application/json", requestBody, "application/json", true);
        }

19 Source : ControllerApi.cs
with Apache License 2.0
from Appdynamics

public string GetSnapshotSegments(string requestGUID, DateTime startTime, DateTime endTime, int durationBetweenTimes)
        {
            string requestJSONTemplate =
@"{{
    ""guids"": [""{0}""],
    ""needExitCalls"": true,
    ""needProps"": true,
    ""rangeSpecifier"": {{
        ""type"": ""BETWEEN_TIMES"",
        ""startTime"": ""{1:o}"",
        ""endTime"": ""{2:o}"",
        ""durationInMinutes"": {3}
    }}
}}";
            string requestBody = String.Format(requestJSONTemplate,
                requestGUID,
                startTime.ToUniversalTime(),
                endTime.ToUniversalTime(),
                durationBetweenTimes);

            return this.apiPOST("controller/restui/snapshot/getFilteredRSDListData", "application/json", requestBody, "application/json", true);
        }

19 Source : FileSelector.cs
with Apache License 2.0
from Appdynamics

private static SelectionCriterion _ParseCriterion(String s)
        {
            if (s == null) return null;

            // inject spaces after open paren and before close paren, etc
            s = NormalizeCriteriaExpression(s);

            // no spaces in the criteria is shorthand for filename glob
            if (s.IndexOf(" ") == -1)
                s = "name = " + s;

            // split the expression into tokens
            string[] tokens = s.Trim().Split(' ', '\t');

            if (tokens.Length < 3) throw new ArgumentException(s);

            SelectionCriterion current = null;

            LogicalConjunction pendingConjunction = LogicalConjunction.NONE;

            ParseState state;
            var stateStack = new System.Collections.Generic.Stack<ParseState>();
            var critStack = new System.Collections.Generic.Stack<SelectionCriterion>();
            stateStack.Push(ParseState.Start);

            for (int i = 0; i < tokens.Length; i++)
            {
                string tok1 = tokens[i].ToLower(CultureInfo.InvariantCulture);
                switch (tok1)
                {
                    case "and":
                    case "xor":
                    case "or":
                        state = stateStack.Peek();
                        if (state != ParseState.CriterionDone)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        if (tokens.Length <= i + 3)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        pendingConjunction = (LogicalConjunction)Enum.Parse(typeof(LogicalConjunction), tokens[i].ToUpper(CultureInfo.InvariantCulture), true);
                        current = new CompoundCriterion { Left = current, Right = null, Conjunction = pendingConjunction };
                        stateStack.Push(state);
                        stateStack.Push(ParseState.ConjunctionPending);
                        critStack.Push(current);
                        break;

                    case "(":
                        state = stateStack.Peek();
                        if (state != ParseState.Start && state != ParseState.ConjunctionPending && state != ParseState.OpenParen)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        if (tokens.Length <= i + 4)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        stateStack.Push(ParseState.OpenParen);
                        break;

                    case ")":
                        state = stateStack.Pop();
                        if (stateStack.Peek() != ParseState.OpenParen)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        stateStack.Pop();
                        stateStack.Push(ParseState.CriterionDone);
                        break;

                    case "atime":
                    case "ctime":
                    case "mtime":
                        if (tokens.Length <= i + 2)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        DateTime t;
                        try
                        {
                            t = DateTime.ParseExact(tokens[i + 2], "yyyy-MM-dd-HH:mm:ss", null);
                        }
                        catch (FormatException)
                        {
                            try
                            {
                                t = DateTime.ParseExact(tokens[i + 2], "yyyy/MM/dd-HH:mm:ss", null);
                            }
                            catch (FormatException)
                            {
                                try
                                {
                                    t = DateTime.ParseExact(tokens[i + 2], "yyyy/MM/dd", null);
                                }
                                catch (FormatException)
                                {
                                    try
                                    {
                                        t = DateTime.ParseExact(tokens[i + 2], "MM/dd/yyyy", null);
                                    }
                                    catch (FormatException)
                                    {
                                        t = DateTime.ParseExact(tokens[i + 2], "yyyy-MM-dd", null);
                                    }
                                }
                            }
                        }
                        t= DateTime.SpecifyKind(t, DateTimeKind.Local).ToUniversalTime();
                        current = new TimeCriterion
                        {
                            Which = (WhichTime)Enum.Parse(typeof(WhichTime), tokens[i], true),
                            Operator = (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]),
                            Time = t
                        };
                        i += 2;
                        stateStack.Push(ParseState.CriterionDone);
                        break;


                    case "length":
                    case "size":
                        if (tokens.Length <= i + 2)
                            throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                        Int64 sz = 0;
                        string v = tokens[i + 2];
                        if (v.EndsWith("K", StringComparison.OrdinalIgnoreCase))
                            sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024;
                        else if (v.EndsWith("KB", StringComparison.OrdinalIgnoreCase))
                            sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024;
                        else if (v.EndsWith("M", StringComparison.OrdinalIgnoreCase))
                            sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024 * 1024;
                        else if (v.EndsWith("MB", StringComparison.OrdinalIgnoreCase))
                            sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024 * 1024;
                        else if (v.EndsWith("G", StringComparison.OrdinalIgnoreCase))
                            sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024 * 1024 * 1024;
                        else if (v.EndsWith("GB", StringComparison.OrdinalIgnoreCase))
                            sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024 * 1024 * 1024;
                        else sz = Int64.Parse(tokens[i + 2]);

                        current = new SizeCriterion
                        {
                            Size = sz,
                            Operator = (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1])
                        };
                        i += 2;
                        stateStack.Push(ParseState.CriterionDone);
                        break;

                    case "filename":
                    case "name":
                        {
                            if (tokens.Length <= i + 2)
                                throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                            ComparisonOperator c =
                                (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]);

                            if (c != ComparisonOperator.NotEqualTo && c != ComparisonOperator.EqualTo)
                                throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                            string m = tokens[i + 2];

                            // handle single-quoted filespecs (used to include
                            // spaces in filename patterns)
                            if (m.StartsWith("'") && m.EndsWith("'"))
                            {
                                // trim off leading and trailing single quotes and
                                // revert the control characters to spaces.
                                m = m.Substring(1, m.Length - 2)
                                    .Replace("\u0006", " ");
                            }

                            // if (m.StartsWith("'"))
                            //     m = m.Replace("\u0006", " ");

                            current = new NameCriterion
                            {
                                MatchingFileSpec = m,
                                Operator = c
                            };
                            i += 2;
                            stateStack.Push(ParseState.CriterionDone);
                        }
                        break;

#if !SILVERLIGHT
                    case "attrs":
                    case "attributes":
#endif
                    case "type":
                        {
                            if (tokens.Length <= i + 2)
                                throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

                            ComparisonOperator c =
                                (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]);

                            if (c != ComparisonOperator.NotEqualTo && c != ComparisonOperator.EqualTo)
                                throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));

#if SILVERLIGHT
                            current = (SelectionCriterion) new TypeCriterion
                                    {
                                        AttributeString = tokens[i + 2],
                                        Operator = c
                                    };
#else
                            current = (tok1 == "type")
                                ? (SelectionCriterion) new TypeCriterion
                                    {
                                        AttributeString = tokens[i + 2],
                                        Operator = c
                                    }
                                : (SelectionCriterion) new AttributesCriterion
                                    {
                                        AttributeString = tokens[i + 2],
                                        Operator = c
                                    };
#endif
                            i += 2;
                            stateStack.Push(ParseState.CriterionDone);
                        }
                        break;

                    case "":
                        // NOP
                        stateStack.Push(ParseState.Whitespace);
                        break;

                    default:
                        throw new ArgumentException("'" + tokens[i] + "'");
                }

                state = stateStack.Peek();
                if (state == ParseState.CriterionDone)
                {
                    stateStack.Pop();
                    if (stateStack.Peek() == ParseState.ConjunctionPending)
                    {
                        while (stateStack.Peek() == ParseState.ConjunctionPending)
                        {
                            var cc = critStack.Pop() as CompoundCriterion;
                            cc.Right = current;
                            current = cc; // mark the parent as current (walk up the tree)
                            stateStack.Pop();   // the conjunction is no longer pending

                            state = stateStack.Pop();
                            if (state != ParseState.CriterionDone)
                                throw new ArgumentException("??");
                        }
                    }
                    else stateStack.Push(ParseState.CriterionDone);  // not sure?
                }

                if (state == ParseState.Whitespace)
                    stateStack.Pop();
            }

            return current;
        }

19 Source : FileSelector.cs
with Apache License 2.0
from Appdynamics

internal override bool Evaluate(string filename)
        {
            DateTime x;
            switch (Which)
            {
                case WhichTime.atime:
                    x = System.IO.File.GetLastAccessTime(filename).ToUniversalTime();
                    break;
                case WhichTime.mtime:
                    x = System.IO.File.GetLastWriteTime(filename).ToUniversalTime();
                    break;
                case WhichTime.ctime:
                    x = System.IO.File.GetCreationTime(filename).ToUniversalTime();
                    break;
                default:
                    throw new ArgumentException("Operator");
            }
            CriterionTrace("TimeCriterion({0},{1})= {2}", filename, Which.ToString(), x);
            return _Evaluate(x);
        }

19 Source : ZipEntry.cs
with Apache License 2.0
from Appdynamics

public void SetEntryTimes(DateTime created, DateTime accessed, DateTime modified)
        {
            _ntfsTimesAreSet = true;
            if (created == _zeroHour && created.Kind == _zeroHour.Kind) created = _win32Epoch;
            if (accessed == _zeroHour && accessed.Kind == _zeroHour.Kind) accessed = _win32Epoch;
            if (modified == _zeroHour && modified.Kind == _zeroHour.Kind) modified = _win32Epoch;
            _Ctime = created.ToUniversalTime();
            _Atime = accessed.ToUniversalTime();
            _Mtime = modified.ToUniversalTime();
            _LastModified = _Mtime;
            if (!_emitUnixTimes && !_emitNtfsTimes)
                _emitNtfsTimes = true;
            _metadataChanged = true;
        }

19 Source : ZipEntry.cs
with Apache License 2.0
from Appdynamics

private static ZipEntry Create(string nameInArchive, ZipEntrySource source, Object arg1, Object arg2)
        {
            if (String.IsNullOrEmpty(nameInArchive))
                throw new Ionic.Zip.ZipException("The entry name must be non-null and non-empty.");

            ZipEntry entry = new ZipEntry();

            // workitem 7071
            // workitem 7926 - "version made by" OS should be zero for compat with WinZip
            entry._VersionMadeBy = (0 << 8) + 45; // indicates the attributes are FAT Attributes, and v4.5 of the spec
            entry._Source = source;
            entry._Mtime = entry._Atime = entry._Ctime = DateTime.UtcNow;

            if (source == ZipEntrySource.Stream)
            {
                entry._sourceStream = (arg1 as Stream);         // may  or may not be null
            }
            else if (source == ZipEntrySource.WriteDelegate)
            {
                entry._WriteDelegate = (arg1 as WriteDelegate); // may  or may not be null
            }
            else if (source == ZipEntrySource.JitStream)
            {
                entry._OpenDelegate = (arg1 as OpenDelegate);   // may  or may not be null
                entry._CloseDelegate = (arg2 as CloseDelegate); // may  or may not be null
            }
            else if (source == ZipEntrySource.ZipOutputStream)
            {
            }
            // workitem 9073
            else if (source == ZipEntrySource.None)
            {
                // make this a valid value, for later.
                entry._Source = ZipEntrySource.FileSystem;
            }
            else
            {
                String filename = (arg1 as String);   // must not be null

                if (String.IsNullOrEmpty(filename))
                    throw new Ionic.Zip.ZipException("The filename must be non-null and non-empty.");

                try
                {
                    // The named file may or may not exist at this time.  For
                    // example, when adding a directory by name.  We test existence
                    // when necessary: when saving the ZipFile, or when getting the
                    // attributes, and so on.

#if NETCF
                    // workitem 6878
                    // Ionic.Zip.SharedUtilities.AdjustTime_Win32ToDotNet
                    entry._Mtime = File.GetLastWriteTime(filename).ToUniversalTime();
                    entry._Ctime = File.GetCreationTime(filename).ToUniversalTime();
                    entry._Atime = File.GetLastAccessTime(filename).ToUniversalTime();

                    // workitem 7071
                    // can only get attributes of files that exist.
                    if (File.Exists(filename) || Directory.Exists(filename))
                        entry._ExternalFileAttrs = (int)NetCfFile.GetAttributes(filename);

#elif SILVERLIGHT
                    entry._Mtime =
                        entry._Ctime =
                        entry._Atime = System.DateTime.UtcNow;
                    entry._ExternalFileAttrs = (int)0;
#else
                    // workitem 6878??
                    entry._Mtime = File.GetLastWriteTime(filename).ToUniversalTime();
                    entry._Ctime = File.GetCreationTime(filename).ToUniversalTime();
                    entry._Atime = File.GetLastAccessTime(filename).ToUniversalTime();

                    // workitem 7071
                    // can only get attributes on files that exist.
                    if (File.Exists(filename) || Directory.Exists(filename))
                        entry._ExternalFileAttrs = (int)File.GetAttributes(filename);

#endif
                    entry._ntfsTimesAreSet = true;

                    entry._LocalFileName = Path.GetFullPath(filename); // workitem 8813

                }
                catch (System.IO.PathTooLongException ptle)
                {
                    // workitem 14035
                    var msg = String.Format("The path is too long, filename={0}",
                                            filename);
                    throw new ZipException(msg, ptle);
                }

            }

            entry._LastModified = entry._Mtime;
            entry._FileNameInArchive = SharedUtilities.NormalizePathForUseInZipFile(nameInArchive);
            // We don't actually slurp in the file data until the caller invokes Write on this entry.

            return entry;
        }

19 Source : MongoObjectId.cs
with MIT License
from aprilyush

public static DateTime ToUniversalTime( DateTime dateTime ) {
            if( dateTime == DateTime.MinValue ) {
                return DateTime.SpecifyKind( DateTime.MinValue, DateTimeKind.Utc );
            }
            else if( dateTime == DateTime.MaxValue ) {
                return DateTime.SpecifyKind( DateTime.MaxValue, DateTimeKind.Utc );
            }
            else {
                return dateTime.ToUniversalTime();
            }
        }

19 Source : EntityTime.cs
with MIT License
from araditc

public DateTime GetTime(Jid jid) {
			jid.ThrowIfNull("jid");
			if (!ecapa.Supports(jid, Extension.EnreplacedyTime)) {
				throw new NotSupportedException("The XMPP enreplacedy does not support " +
					"the 'Enreplacedy Time' extension.");
			}
			Iq iq = im.IqRequest(IqType.Get, jid, im.Jid,
				Xml.Element("time", "urn:xmpp:time"));
			if (iq.Type == IqType.Error)
				throw Util.ExceptionFromError(iq, "The time could not be retrieved.");
			var time = iq.Data["time"];
			if (time == null || time["tzo"] == null || time["utc"] == null)
				throw new XmppException("Erroneous IQ response.");
			string tzo = time["tzo"].InnerText;
			string utc = time["utc"].InnerText;
			// Try to parse utc into datetime, tzo into timespan.
			try {
				DateTime dt = DateTime.Parse(utc).ToUniversalTime();
				TimeSpan sp = TimeSpan.Parse(tzo.TrimStart('+'));
				return dt.Add(sp);
			} catch (FormatException e) {
				throw new XmppException("Invalid tzo or utc value.", e);
			}
		}

19 Source : EntityTime.cs
with MIT License
from araditc

public bool Input(Iq stanza) {
			if (stanza.Type != IqType.Get)
				return false;
			var e = stanza.Data["time"];
			if (e == null || e.NamespaceURI != "urn:xmpp:time")
				return false;
			TimeSpan span = TimeZoneInfo.Local.BaseUtcOffset;
			// The numeric time zone offset from UTC.
			string tzo = ((span < TimeSpan.Zero) ? "-" : "+") +
				span.ToString(@"hh\:mm");
			// The UTC time according to the responding enreplacedy.
			string utc = DateTime.UtcNow.ToUniversalTime()
				.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'''Z'");
			var time = Xml.Element("time", "urn:xmpp:time")
				.Child(Xml.Element("tzo").Text(tzo))
				.Child(Xml.Element("utc").Text(utc));
			// Send the IQ response.
			im.IqResult(stanza, time);
			return true;
		}

See More Examples