1、.NET(C#)中可空类型
可空类型(Nullable Type)表示在值类型的正常取值范围,还可为null值,声明一个可空类型的语法如下:T? myNullableNum = rangedNum/new T?() or null; //其中T需要为值类型
1) 可空类型是泛型结构Nullable的实例,其声明为:public struct Nullable where T : struct,语法T?是Nullable的简写形式//声明一个可空整DateTime?类型
DateTime? date = DateTime.UtcNow;
//Nullable dateTime = new Nullable();
2) 可空类型包含实例成员
HasValue:只读属性,判断是否有值,如果当前值非空,返回true,否则返回false
Value:只读属性,如果当前值非空,可以正常访问,否则说明Value不包含有意义的值,此时访问Value时会抛出异常InvalidOperationException
GetValueOrDefault():实例方法,如果当前值非空(HasValue为true),返回Vlaue的值,否则返回T类型的默认值(即私有字段value的默认值)
GetValueOrDefault (T defaultValue):实例方法,如果当前值非空(HasValue为false),返回Vlaue的值,否则返回默认值defaultValue
3) 转成基础类型int? myNullableInt = null;
int myInt = (int)myNullableInt;
int myInt = myNullableInt.Value;
//以上两种方式,在可空类型实例为null时会抛出异常,可以使用以下方式代替
int myInt = myNullableInt.GetValueOrDefault(); //其重载方法可以传入默认值
2、通过ToUniversalTime将可空类型DateTime?转成有时区时间字符串
ToUniversalTime():将当前DateTime对象的值转换为世界标准时间(UTC)。
1) ToUniversalTime()使用示例代码using System;
class Example
{
static void Main(){
DateTime localDateTime, univDateTime;
Console.WriteLine("Enter a date and time.");
string strDateTime = Console.ReadLine();
try {
localDateTime = DateTime.Parse(strDateTime);
univDateTime = localDateTime.ToUniversalTime();
Console.WriteLine("{0} local time is {1} universal time.",
localDateTime,
univDateTime);
}
catch (FormatException) {
Console.WriteLine("Invalid format.");
return;
}
Console.WriteLine("Enter a date and time in universal time.");
strDateTime = Console.ReadLine();
try {
univDateTime = DateTime.Parse(strDateTime);
localDateTime = univDateTime.ToLocalTime();
Console.WriteLine("{0} universal time is {1} local time.",
univDateTime,
localDateTime);
}
catch (FormatException) {
Console.WriteLine("Invalid format.");
return;
}
}
}
//Enter a date and time.
//12/10/2015 6:18 AM
//2015/12/10 上午6:18:00 local time is 2015/12/9 下午10:18:00 universal time.
//Enter a date and time in universal time.
//12/20/2015 6:42:00
//2015/12/20 上午6:42:00 universal time is 2015/12/20 下午2:42:00 local time.
2) 将DateTime?转成有时区时间字符串var dateInUTCString = date.HasValue ? date.Value.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'") : "";
或者var dateInUTCString = date?.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'") ?? "";
或者string dateInUTCString =
date?.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture)
?? "";
或者string dateInUTCString = date?.ToUniversalTime().ToString("O") ?? "";
"O"或"o" : 标准格式说明符使用保留时区信息并发出符合ISO 8601的结果字符串的模式表示自定义日期和时间格式字符串。
参考文档://2008-04-24T15:52:19.1562500+08:00
System.DateTime.Now.ToString("o");
System.DateTime.Now.ToString("O");
相关文档: