本文主要介绍一下.NET(C#)中,可空(null)类型的用法以及调用ToUniversalTime()将可空(null)日期时间类型DateTime?转成字符串的方法,以及转换的示例代码。

1、.NET(C#)中可空类型

可空类型(Nullable Type)表示在值类型的正常取值范围,还可为null值,声明一个可空类型的语法如下:

T? myNullableNum = rangedNum/new T?() or null; //其中T需要为值类型

1) 可空类型是泛型结构Nullable<T>的实例,其声明为:public struct Nullable<T> where T : struct,语法T?Nullable<T>的简写形式

//声明一个可空整DateTime?类型
DateTime? date = DateTime.UtcNow;
//Nullable<DateTime> dateTime = new Nullable<DateTime>();

2) 可空类型包含实例成员

HasValue:只读属性,判断是否有值,如果当前值非空,返回true,否则返回false

Value:只读属性,如果当前值非空,可以正常访问,否则说明Value不包含有意义的值,此时访问Value时会抛出异常InvalidOperationException

GetValueOrDefault():实例方法,如果当前值非空(HasValuetrue),返回Vlaue的值,否则返回T类型的默认值(即私有字段value的默认值)

GetValueOrDefault (T defaultValue):实例方法,如果当前值非空(HasValuefalse),返回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?转成有时区时间字符串

ToString()参数格式占位符说明参考文档https://www.cjavapy.com/article/310/

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的结果字符串的模式表示自定义日期和时间格式字符串。

参考文档:

standard-date-and-time-format-strings#Roundtrip

system.datetime.touniversaltime

//2008-04-24T15:52:19.1562500+08:00     
System.DateTime.Now.ToString("o");     
System.DateTime.Now.ToString("O");  

相关文档:

.NET(C#)时间日期字符串(String)转换成Datetime异常报错问题

推荐文档

相关文档

大家感兴趣的内容

随机列表