简体   繁体   中英

How to Export/Import DateTime in DataSet C#

I've two applications, 1st exports DataSet to file, 2nd reads that file to DataSet. Both application have CultureInfo set to "en-US", as well as DataSet.Locale is "en-US".

In first application I have DateTime field:

dt.Columns.Add("DateCreated", typeof(DateTime));

than write to file:

ds.WriteXml(fileName);

In second app:

    ds.ReadXml(reader);

and when I try to read DateTime field from DataRow:

DateTime? dateCreated = Convert.ToDateTime(dr["DateCreated"]);

it throws an exception:

'Convert.ToDateTime(dr["DateCreated"])' threw an exception of type 'System.FormatException' same as cast, or when I specify CultureInfo. Also it doesn't convert when I specify to save DataSet with Schema.

Date Value in this field is in format: "2017-06-11T08:10:06.2212339 03:00"

Why this happens and is it possible to convert it to DateTime without specifying DateFormat string? Thank you!

The UTC date string format seems incorrect without using positive or negative sign in time zone offset part, and will throw FormatException with given message String was not recognized as a valid DateTime :

2017-06-11T08:10:06.2212339 03:00
                            ^
                            missing sign offset here

If date formats given by DataRow are fixed in positive time offset and you just want to read them, use String.Insert to insert offset sign before offset part like this:

String date = (dr["DateCreated"] ?? String.Empty).ToString();

if (!String.IsNullOrEmpty(date))
{
    date = date.Insert((date.Length - 5), "+");

    // NB: Convert.ToDateTime will give same value as DateTime.ParseExact here
    DateTime? dateCreated = DateTime.ParseExact(date, "yyyy-MM-ddTHH:mm:ss.FFFFFFF zzzz", 
                            CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
}

The output string on date & dateCreated should be like this (in UTC basis):

date: 2017-06-11T08:10:06.2212339 +03:00

dateCreated: 6/11/2017 5:10:06 AM

NB: Convert.ToDateTime probably uses Object argument instead of string in case of DataRow input, so this code may applicable if dr["DateCreated"] has certainly doesn't have null value:

DateTime? dateCreated = Convert.ToDateTime(dr["DateCreated"].ToString().Insert((date.Length - 6), "+"));

Parsing example: .NET Fiddle Demo

Related issues:

Custom DateTime formats when using DataSet.WriteXml in .NET

Reading XML into Datatable gives incorrect DateTime when the time has Time Zone info

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM