本文整理汇总了C#中DateTime.ToUniversalTime方法的典型用法代码示例。如果您正苦于以下问题:C# DateTime.ToUniversalTime方法的具体用法?C# DateTime.ToUniversalTime怎么用?C# DateTime.ToUniversalTime使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DateTime
的用法示例。
在下文中一共展示了DateTime.ToUniversalTime方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SamlAuthenticationStatement
public SamlAuthenticationStatement(SamlSubject samlSubject,
string authenticationMethod,
DateTime authenticationInstant,
string dnsAddress,
string ipAddress,
IEnumerable<SamlAuthorityBinding> authorityBindings)
: base(samlSubject)
{
if (string.IsNullOrEmpty(authenticationMethod))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("authenticationMethod", SR.GetString(SR.SAMLAuthenticationStatementMissingAuthenticationMethod));
this.authenticationMethod = authenticationMethod;
this.authenticationInstant = authenticationInstant.ToUniversalTime();
this.dnsAddress = dnsAddress;
this.ipAddress = ipAddress;
if (authorityBindings != null)
{
foreach (SamlAuthorityBinding binding in authorityBindings)
{
if (binding == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLEntityCannotBeNullOrEmpty, XD.SamlDictionary.Assertion.Value));
this.authorityBindings.Add(binding);
}
}
CheckObjectValidity();
}
示例2: SettingUpdatesProperties
public void SettingUpdatesProperties()
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.All(TimeFunctions(requiresRoundtripping: true), (tuple) =>
{
DateTime dt = new DateTime(2014, 12, 1, 12, 0, 0, tuple.Item3);
tuple.Item1(testFile, dt);
var result = tuple.Item2(testFile);
Assert.Equal(dt, result);
Assert.Equal(dt.ToLocalTime(), result.ToLocalTime());
// File and Directory UTC APIs treat a DateTimeKind.Unspecified as UTC whereas
// ToUniversalTime treats it as local.
if (tuple.Item3 == DateTimeKind.Unspecified)
{
Assert.Equal(dt, result.ToUniversalTime());
}
else
{
Assert.Equal(dt.ToUniversalTime(), result.ToUniversalTime());
}
});
}
示例3: SettingUpdatesProperties
public void SettingUpdatesProperties()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.All(TimeFunctions(requiresRoundtripping: true), (tuple) =>
{
DateTime dt = new DateTime(2014, 12, 1, 12, 0, 0, tuple.Item3);
tuple.Item1(testDir, dt);
var result = tuple.Item2(testDir);
Assert.Equal(dt, result);
Assert.Equal(dt.ToLocalTime(), result.ToLocalTime());
Assert.Equal(dt.ToUniversalTime(), result.ToUniversalTime());
});
}
示例4: SettingUpdatesProperties
public void SettingUpdatesProperties()
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.All(TimeFunctions(), (tuple) =>
{
DateTime dt = new DateTime(2014, 12, 1, 12, 0, 0, tuple.Item3);
tuple.Item1(testFile.FullName, dt);
var result = tuple.Item2(testFile.FullName);
Assert.Equal(dt, result);
Assert.Equal(dt.ToLocalTime(), result.ToLocalTime());
Assert.Equal(dt.ToUniversalTime(), result.ToUniversalTime());
});
}
示例5: GetIntDate
/// <summary>
/// Per JWT spec:
/// Gets the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the desired date/time.
/// </summary>
/// <param name="datetime">The DateTime to convert to seconds.</param>
/// <remarks>if dateTimeUtc less than UnixEpoch, return 0</remarks>
/// <returns>the number of seconds since Unix Epoch.</returns>
public static long GetIntDate(DateTime datetime)
{
DateTime dateTimeUtc = datetime;
if (datetime.Kind != DateTimeKind.Utc)
{
dateTimeUtc = datetime.ToUniversalTime();
}
if (dateTimeUtc.ToUniversalTime() <= UnixEpoch)
{
return 0;
}
return (long)(dateTimeUtc - UnixEpoch).TotalSeconds;
}
开发者ID:richardschneider,项目名称:azure-activedirectory-identitymodel-extensions-for-dotnet,代码行数:22,代码来源:EpochTime.cs
示例6: MockFile_SetCreationTime_ShouldAffectCreationTimeUtc
public void MockFile_SetCreationTime_ShouldAffectCreationTimeUtc()
{
// Arrange
string path = XFS.Path(@"c:\something\demo.txt");
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
{
{ path, new MockFileData("Demo text content") }
});
var file = new MockFile(fileSystem);
// Act
var creationTime = new DateTime(2010, 6, 4, 13, 26, 42);
file.SetCreationTime(path, creationTime);
var result = file.GetCreationTimeUtc(path);
// Assert
Assert.AreEqual(creationTime.ToUniversalTime(), result);
}
示例7: SamlConditions
public SamlConditions(DateTime notBefore, DateTime notOnOrAfter,
IEnumerable<SamlCondition> conditions
)
{
this.notBefore = notBefore.ToUniversalTime();
this.notOnOrAfter = notOnOrAfter.ToUniversalTime();
if (conditions != null)
{
foreach (SamlCondition condition in conditions)
{
if (condition == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLEntityCannotBeNullOrEmpty, XD.SamlDictionary.Condition.Value));
this.conditions.Add(condition);
}
}
}
示例8: MembershipUser
public MembershipUser (string providerName, string name, object providerUserKey, string email,
string passwordQuestion, string comment, bool isApproved, bool isLockedOut,
DateTime creationDate, DateTime lastLoginDate, DateTime lastActivityDate,
DateTime lastPasswordChangedDate, DateTime lastLockoutDate)
{
this.providerName = providerName;
this.name = name;
this.providerUserKey = providerUserKey;
this.email = email;
this.passwordQuestion = passwordQuestion;
this.comment = comment;
this.isApproved = isApproved;
this.isLockedOut = isLockedOut;
this.creationDate = creationDate.ToUniversalTime ();
this.lastLoginDate = lastLoginDate.ToUniversalTime ();
this.lastActivityDate = lastActivityDate.ToUniversalTime ();
this.lastPasswordChangedDate = lastPasswordChangedDate.ToUniversalTime ();
this.lastLockoutDate = lastLockoutDate.ToUniversalTime ();
}
示例9: ProfileInfo
public ProfileInfo(string username, bool isAnonymous, DateTime lastActivityDate, DateTime lastUpdatedDate, int size)
{
if( username != null )
{
username = username.Trim();
}
_UserName = username;
if (lastActivityDate.Kind == DateTimeKind.Local) {
lastActivityDate = lastActivityDate.ToUniversalTime();
}
_LastActivityDate = lastActivityDate;
if (lastUpdatedDate.Kind == DateTimeKind.Local) {
lastUpdatedDate = lastUpdatedDate.ToUniversalTime();
}
_LastUpdatedDate = lastUpdatedDate;
_IsAnonymous = isAnonymous;
_Size = size;
}
示例10: DefaultODataETagHandler_DateTime_RoundTrips
[InlineData("China Standard Time")] // +8:00
public void DefaultODataETagHandler_DateTime_RoundTrips(string timeZoneId)
{
// Arrange
TimeZoneInfoHelper.TimeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
DateTime value = new DateTime(2015, 2, 17, 1, 2, 3, DateTimeKind.Utc);
DefaultODataETagHandler handler = new DefaultODataETagHandler();
Dictionary<string, object> properties = new Dictionary<string, object> { { "Any", value } };
// Act
EntityTagHeaderValue etagHeaderValue = handler.CreateETag(properties);
IList<object> values = handler.ParseETag(etagHeaderValue).Select(p => p.Value).ToList();
// Assert
Assert.True(etagHeaderValue.IsWeak);
Assert.Equal(1, values.Count);
DateTimeOffset result = Assert.IsType<DateTimeOffset>(values[0]);
Assert.Equal(new DateTimeOffset(value.ToUniversalTime()).ToOffset(TimeZoneInfoHelper.TimeZone.BaseUtcOffset),
result);
}
示例11: SamlAssertion
public SamlAssertion(
string assertionId,
string issuer,
DateTime issueInstant,
SamlConditions samlConditions,
SamlAdvice samlAdvice,
IEnumerable<SamlStatement> samlStatements
)
{
if (string.IsNullOrEmpty(assertionId))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLAssertionIdRequired));
if (!IsAssertionIdValid(assertionId))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLAssertionIDIsInvalid, assertionId));
if (string.IsNullOrEmpty(issuer))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLAssertionIssuerRequired));
if (samlStatements == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlStatements");
}
this.assertionId = assertionId;
this.issuer = issuer;
this.issueInstant = issueInstant.ToUniversalTime();
this.conditions = samlConditions;
this.advice = samlAdvice;
foreach (SamlStatement samlStatement in samlStatements)
{
if (samlStatement == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLEntityCannotBeNullOrEmpty, XD.SamlDictionary.Statement.Value));
this.statements.Add(samlStatement);
}
if (this.statements.Count == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLAssertionRequireOneStatement));
}
示例12: ExpandPredefinedFormat
// Expand a pre-defined format string (like "D" for long date) to the real format that
// we are going to use in the date time parsing.
// This method also convert the dateTime if necessary (e.g. when the format is in Universal time),
// and change dtfi if necessary (e.g. when the format should use invariant culture).
//
private static String ExpandPredefinedFormat(String format, ref DateTime dateTime, ref DateTimeFormatInfo dtfi, ref TimeSpan offset)
{
switch (format[0])
{
case 'o':
case 'O': // Round trip format
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
case 'r':
case 'R': // RFC 1123 Standard
if (offset != NullOffset)
{
// Convert to UTC invariants mean this will be in range
dateTime = dateTime - offset;
}
else if (dateTime.Kind == DateTimeKind.Local)
{
InvalidFormatForLocal(format, dateTime);
}
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
case 's': // Sortable without Time Zone Info
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
case 'u': // Universal time in sortable format.
if (offset != NullOffset)
{
// Convert to UTC invariants mean this will be in range
dateTime = dateTime - offset;
}
else if (dateTime.Kind == DateTimeKind.Local)
{
InvalidFormatForLocal(format, dateTime);
}
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
case 'U': // Universal time in culture dependent format.
if (offset != NullOffset)
{
// This format is not supported by DateTimeOffset
throw new FormatException(SR.Format_InvalidString);
}
// Universal time is always in Greogrian calendar.
//
// Change the Calendar to be Gregorian Calendar.
//
dtfi = (DateTimeFormatInfo)dtfi.Clone();
if (dtfi.Calendar.GetType() != typeof(GregorianCalendar))
{
dtfi.Calendar = GregorianCalendar.GetDefaultInstance();
}
dateTime = dateTime.ToUniversalTime();
break;
}
format = GetRealFormat(format, dtfi);
return (format);
}
示例13: GetAllDateTimes
internal static String[] GetAllDateTimes(DateTime dateTime, char format, IFormatProvider provider)
{
DateTimeFormatInfo dtfi = provider == null ? DateTimeFormatInfo.CurrentInfo : DateTimeFormatInfo.GetInstance(provider);
String[] allFormats = null;
String[] results = null;
switch (format)
{
case 'd':
case 'D':
case 'f':
case 'F':
case 'g':
case 'G':
case 'm':
case 'M':
case 't':
case 'T':
case 'y':
case 'Y':
allFormats = dtfi.GetAllDateTimePatterns(format);
results = new String[allFormats.Length];
for (int i = 0; i < allFormats.Length; i++)
{
results[i] = Format(dateTime, allFormats[i], dtfi);
}
break;
case 'U':
DateTime universalTime = dateTime.ToUniversalTime();
allFormats = dtfi.GetAllDateTimePatterns(format);
results = new String[allFormats.Length];
for (int i = 0; i < allFormats.Length; i++)
{
results[i] = Format(universalTime, allFormats[i], dtfi);
}
break;
//
// The following ones are special cases because these patterns are read-only in
// DateTimeFormatInfo.
//
case 'r':
case 'R':
case 'o':
case 'O':
case 's':
case 'u':
results = new String[] { Format(dateTime, new String(new char[] { format }), dtfi) };
break;
default:
throw new FormatException(SR.Format_InvalidString);
}
return (results);
}
示例14: CreateCookieFromSecurityContext
public byte[] CreateCookieFromSecurityContext(UniqueId contextId, string id, byte[] key, DateTime tokenEffectiveTime,
DateTime tokenExpirationTime, UniqueId keyGeneration, DateTime keyEffectiveTime, DateTime keyExpirationTime,
ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies)
{
if (contextId == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contextId");
}
if (key == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("key");
}
MemoryStream stream = new MemoryStream();
XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(stream, SctClaimDictionary.Instance, null);
SctClaimDictionary dictionary = SctClaimDictionary.Instance;
writer.WriteStartElement(dictionary.SecurityContextSecurityToken, dictionary.EmptyString);
writer.WriteStartElement(dictionary.Version, dictionary.EmptyString);
writer.WriteValue(SupportedPersistanceVersion);
writer.WriteEndElement();
if (id != null)
writer.WriteElementString(dictionary.Id, dictionary.EmptyString, id);
XmlHelper.WriteElementStringAsUniqueId(writer, dictionary.ContextId, dictionary.EmptyString, contextId);
writer.WriteStartElement(dictionary.Key, dictionary.EmptyString);
writer.WriteBase64(key, 0, key.Length);
writer.WriteEndElement();
if (keyGeneration != null)
{
XmlHelper.WriteElementStringAsUniqueId(writer, dictionary.KeyGeneration, dictionary.EmptyString, keyGeneration);
}
XmlHelper.WriteElementContentAsInt64(writer, dictionary.EffectiveTime, dictionary.EmptyString, tokenEffectiveTime.ToUniversalTime().Ticks);
XmlHelper.WriteElementContentAsInt64(writer, dictionary.ExpiryTime, dictionary.EmptyString, tokenExpirationTime.ToUniversalTime().Ticks);
XmlHelper.WriteElementContentAsInt64(writer, dictionary.KeyEffectiveTime, dictionary.EmptyString, keyEffectiveTime.ToUniversalTime().Ticks);
XmlHelper.WriteElementContentAsInt64(writer, dictionary.KeyExpiryTime, dictionary.EmptyString, keyExpirationTime.ToUniversalTime().Ticks);
AuthorizationContext authContext = null;
if (authorizationPolicies != null)
authContext = AuthorizationContext.CreateDefaultAuthorizationContext(authorizationPolicies);
if (authContext != null && authContext.ClaimSets.Count != 0)
{
DataContractSerializer identitySerializer = DataContractSerializerDefaults.CreateSerializer(typeof(IIdentity), this.knownTypes, int.MaxValue);
DataContractSerializer claimSetSerializer = DataContractSerializerDefaults.CreateSerializer(typeof(ClaimSet), this.knownTypes, int.MaxValue);
DataContractSerializer claimSerializer = DataContractSerializerDefaults.CreateSerializer(typeof(Claim), this.knownTypes, int.MaxValue);
SctClaimSerializer.SerializeIdentities(authContext, dictionary, writer, identitySerializer);
writer.WriteStartElement(dictionary.ClaimSets, dictionary.EmptyString);
for (int i = 0; i < authContext.ClaimSets.Count; i++)
{
SctClaimSerializer.SerializeClaimSet(authContext.ClaimSets[i], dictionary, writer, claimSetSerializer, claimSerializer);
}
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.Flush();
byte[] serializedContext = stream.ToArray();
return this.securityStateEncoder.EncodeSecurityState(serializedContext);
}
示例15: DateToString
// convert Date to String using RFC 1123 pattern
private static string DateToString(DateTime D)
{
DateTimeFormatInfo dateFormat = new DateTimeFormatInfo();
return D.ToUniversalTime().ToString("R", dateFormat);
}