在数组中的字符串列表中,以正确的时区格式获取日期

Getting date in correct formatted for with proper timezone, among list of strings in an a array

我有一组数组。

//this is not hard corded, some times array will have multiple no.of strings in date format.
["vishnu","2016-08-31T18:30:00.000Z","1992","banglore"] 

我有一组字符串,在这些字符串中有一个字符串是日期格式。

我需要做一个 foreach 并且需要检查日期格式的字符串。 如果我们得到日期字符串 "2016-08-30T18:30:00.000Z" 我需要将它转换为基本日期格式但在正确的时区中,这里的日期是 2016-08-31 但我需要的输出是

["vishnu","31/8/2016","1992","banglore"]

不是

//check the difference in date!
["vishnu","30/8/2016","1992","banglore"]

目的是从数组开始,如果string是日期字符串格式,则进行转换

public static void Main(string[] args)
{                        
    string inputString = "2016-08-31T18:30:00.000Z";
    DateTime enteredDate = DateTime.Parse(inputString);
    Console.WriteLine(enteredDate);
    DateTime dDate;

    if (DateTime.TryParse(inputString, out dDate))
    {
        DateTime dtx = enteredDate.ToLocalTime();
        String.Format("{0:d/MM/yyyy}", dDate); 
        Console.WriteLine(dtx);
    }
    else
    {
        Console.WriteLine("Invalid"); // <-- Control flow goes here
    }

   // DateTime dt = convertedDate.ToLocalTime();
}

如果您需要更正时区的DateTime,您可以使用TimezoneInfo.ConvertTime():

string inputString = "2016-08-31T18:30:00.000Z";

DateTime dDate;

if (DateTime.TryParse(inputString, out dDate))
{
    DateTime correctedDateTime = TimeZoneInfo.ConvertTime(dDate, TimeZoneInfo.Local);

    // write this here back into the array using your format
    Console.WriteLine(correctedDateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));
}
else
{
    Console.WriteLine("Invalid"); // <-- Control flow goes here
}

如需进一步参考,请查看此 post。这个答案的灵感来自它使用 TimeZoneInfo.

尝试使用 DateTimeOffset 而不是 DateTime,因为它是为处理时区而构建的。

代码如下:

string inputString = "2016-08-31T18:30:00.000Z";

DateTimeOffset enteredDate = DateTimeOffset.Parse(inputString);
Console.WriteLine(enteredDate);

DateTimeOffset dtx = enteredDate.ToLocalTime();
Console.WriteLine(dtx);

这会在 GMT+09:30 为我生成以下内容:

2016/08/31 18:30:00 +00:00
2016/09/01 04:00:00 +09:30

要在印度时间获取它,试试这个:

DateTimeOffset dtx = enteredDate.ToOffset(TimeSpan.FromHours(5.5));
Console.WriteLine(dtx);

我现在得到 2016/09/01 00:00:00 +05:30

     DateTime dDate;

在foreach旁边做这个操作

        if (DateTime.TryParse(answerString, out dDate))
        {
            DateTime enteredDate = DateTime.Parse(answerString);
            var Date = enteredDate.ToString("dd/MM/yyyy");
            answerString = Date;
           Console.WriteLine(answerString);
        }
    else{
    //operation
        }

感谢 mong zhu