Convert String "2011-06-27T14:03:19.5300000+07:00" To Datetime - c#

I have result string date xml export from database like "2011-06-27T14:03:19.5300000+07:00". How to Convert to format datetime fully(date and time) in C# or VB.Net language datetime?
Please help me
Thanks in Advance

You can use DateTime.Parse
The DateTime.Parse(String) method
tries to convert the string
representation of a date and time
value to its DateTime equivalent. The
string to be parsed can take any of
the following forms:
A string with a date and a time
component.
A string with a date but no time
component.
A string with a time but no date
component.
A string that includes time zone
information and conforms to ISO 8601.
For example, the first of the
following two strings designates the
Coordinated Universal Time (UTC); the
second designates the time in a time
zone seven hours earlier than UTC:
2008-11-01T19:35:00.0000000Z
2008-11-01T19:35:00.0000000-07:00
A string that includes the GMT
designator and conforms to the RFC
1123 time format. For example:
Sat, 01 Nov 2008 19:35:00 GMT
A string that includes the date and
time along with time zone offset
information. For example:
03/01/2009 05:42:00 -5:00

DateTime dt = DateTime.Parse("2011-06-27T14:03:19.5300000+07:00");

The main point is to use DateTime.TryParse
string rawDate = "2011-06-27T14:03:19.5300000+07:00";
DateTime dt = DateTime.MinValue;
if (!DateTime.TryParse(rawDate, out dt))
{
Debug.WriteLine("Unable to parse");
}

If you're using XDocument you can simply call conversion operator to DateTime.

Related

String was not recognized as a valid DateTime in ParseExact with Milliseconds

I have a Date in string format, I need to convert it in DateTime, this is my code:
DateTime dt = DateTime.ParseExact("2018-04-09T09:27:07.247+02:00", "YYYY-MM-DDTHH:mm:ss.SSSZ", System.Globalization.CultureInfo.InvariantCulture).ToUniversalTime();
Console.WriteLine(TimeZoneInfo.ConvertTimeFromUtc(dt, TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time")).ToString());
It works with date like: 2020-08-27T00:00:00+02:00, but it doesn't work with a date like the one in the script because of millis. How should I change the date pattern? I've tried many of them, but I didn't solve.
There are three problems with your code:
Format strings are case sensitive (yyyy represents a 4-digit year, YYYY does not, likewise dd represents a 2-digit day, whereas DD does not).
.sss should be .fff for milliseconds.
You're expecting Z (Zulu) but you're actually getting a time offset ("+02:00"). This means that the format string differs from your datetime string.
I suggest you don't bother with DateTime.ParseExact for ISO8601 datetimes, just use DateTimeOffset's Parse instead (which will obey the time offset and work with ISO8601 datetimes):
DateTimeOffset dt = DateTimeOffset.Parse("2018-04-09T09:27:07.247+02:00", System.Globalization.CultureInfo.InvariantCulture).ToUniversalTime();
Console.WriteLine(TimeZoneInfo.ConvertTimeFromUtc(dt.DateTime, TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time")).ToString());

Format date using DateTime.ToString() based on TimeZone

I read the following question Creating a DateTime in a specific Time Zone in c# and was able to create a DateTime with TimeZone information. But I need to convert the DateTime to string value based on TimeZone.
E.g. I've set the TimeZone as India Standard Time and created a DateTime, when I tried to convert to string using ToString() instead of 13/12/2019 4:00:00 PM, I am getting 12/13/2019 4:00:00 PM. Since I've set the TimeZone as India Standard Time, I would like to display the date in India Format (dd/mm/yyyy) rather than mm/dd/yyyy.
So, how do I format the date based on TimeZone in C#?
Edit: I completely understand that Format and Timezone are different things. But I need to format the DateTime to match user's geography which I can identify using his timezone provided as input.
If you only want a string representation of the DateTime that matches a specific culture you can use the DateTime.ToString(IFormatProvider) overload to specify the target culture you want to use. The date will be formatted accordingly. If you want to format your date and time you want to do this based on the culture of the user and not based on the timezone. People in Kongo and Germany share the same timezone but are formatting their date and time differently.
var myDate = DateTime.Now();
var myDateString = myDate.ToString(new CultureInfo("fr-FR"));
would print the date and time in a french format for example.
You can also format your DateTime with a custom format:
var myDate = DateTime.Now;
var myDateString = myDate.ToString("dd/MM/yyyy hh:mm");
References:
- DateTime.ToString(IFormatProvider)
- DateTime.ToString(string)
- CultureInfo
- Date and time formatting

Parse date time c# with correct timezone and kind

I have a datetime in database which I read using SqlDataReader and then cast it to (DateTime). After the cast its Kind property is DateTimeKind.Unspecified.
Then I have another string which I read from some other source. Its format is like this 2016-01-20T22:20:29.055Z. I do DateTime.Parse("2016-01-20T22:20:29.055Z") and its Kind property is DateTimeKind.Local.
How do I properly parse the both date times for comparison? Do I need to use DateTimeOffsets? How should I parse them?
Thanks
Because SQLReader cannot reasonably infer a DateTimeKind, it leaves it as unspecified. You'll want to use DateTime.SpecifyKind to change the DateTimeKind on your output from the SQLReader to the appropriate value. This works ok if you are only dealing with UTC and one consistent local time zone; otherwise, you really should be using DateTimeOffset in both your code and the SQL Database.
The string "2016-01-20T22:20:29.055Z" is ISO 8601 compliant and is a UTC date; however, DateTime.Parse with only 1 argument can end up performing a conversion to local time. Per the documentation:
Generally, the Parse method returns a DateTime object whose Kind
property is DateTimeKind.Unspecified. However, the Parse method may
also perform time zone conversion and set the value of the Kind
property differently, depending on the values of the s and styles
parameters:
If s contains time zone information, the date and time is converted
to the time in the local time zone and the Kind is DateTimeKind.Local.
If s contains time zone information, and styles includes the
AdjustToUniversalflag, the date and time is converted to Coordinated
Universal Time (UTC) and the Kind is DateTimeKind.Utc.
If s contains the Z or GMT time zone designator, and styles includes
the RoundtripKind flag, the date and time are interpreted as UTC and
the Kind is DateTimeKind.Utc.
Also see UTC gotchas in .NET and SQL Server in Derek Fowler's blog for additional coverage on the topic.
In your second example, 2016-01-20T22:20:29.055Z has timezone information provided with it; the 'Z' at the end indicates that the timestamp is intended for Coordinated Universal Time (UTC). However, DateTime.Parse() will default its conversion using DateTimeKind.Local unless a specific timezone is specified. You can use DateTime.ParseExact to be more specific.
As to why the datetime values in your database are coming out as Unspecified, that's likely because they contain no timezone indication at all. Check to see if your database values specify timezone information, either by using 'Z' at the end or specifying an exact timezone, such as 2016-01-20T22:20:29.055-07:00 (UTC-7).
You can use something like this:
string format = "ddd dd MMM h:mm tt yyyy";
DateTime dateTime = DateTime.ParseExact(dateString, format,
CultureInfo.InvariantCulture);
In format variable, you can put the format you want, and pass it to ParseExact function.
Hope it helps.
You are missing the datetime context (offset) in your database. You should persist it either in a datetimeoffset column or in a datetime column but persisting utc datetimes.
And always better compare two utc datetimes.
I coded a quick C# console app that I pasted in below. This converts a UTC date and time to a string (format similar to the ISO 8601 format described in another post with some extra digits of precision), writes it to a file, reads it from the file (as a string) and then converts it back to a UTC date and time.
It then compares the two UTC Date Time objects, which are both of UTC kind, and they match.
class Program
{
// "2016-01-20T22:20:29.055Z" is ISO 8601 compliant and is a UTC date
const string dtf = "yyyy-MM-ddTHH:mm:ss.fffffffZ";
static void Main(string[] args)
{
string file = #"c:\temp\file.txt";
DateTime dt = DateTime.UtcNow;
using (var sw = new System.IO.StreamWriter(file))
{
sw.WriteLine(dt.ToString(dtf, System.Globalization.CultureInfo.InvariantCulture));
}
DateTime dtin;
using (var sr = new System.IO.StreamReader(file))
{
dtin = DateTime.ParseExact(sr.ReadLine(), dtf, System.Globalization.CultureInfo.InvariantCulture);
}
Console.WriteLine(dt.ToString(dtf) + "\r\n" + dtin.ToString(dtf) + "\r\nEquality:" + (dt == dtin));
Console.ReadLine();
}
}

How to parse a string into a date time format in C#

i have a string which contains date time this...
string S="08/18/2013 24:00:00"
DateTime DT = DateTime.ParseExact(S, "MM/dd/yyyy HH:mm:ss", null);
i want to parse it into date time but shows an exception like this.
The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.
please tell me any solution for this problem.
The problem is with the hour being 24. DateTime doesn't support this, as far as I'm aware.
Options:
Use my Noda Time project which does support 24:00:00, but basically handles it by adding a day (it doesn't preserve a difference between that and "end of previous day")
Keep using DateTime, manually replace "24:00:00" with "00:00:00" when it occurs, and remember to add a day afterwards
If you want to preserve the information that it was actually "end of the day" you'd need to do that separately, and keep the information alongside the DateTime / LocalDateTime.
You should also parse with the invariant culture as other answers have suggested - you're not trying to parse a culture-specific string; you know the exact separators etc.
string S="08/18/2013 00:00:00"; // here is the first problem occurred
DateTime DT = DateTime.ParseExact(S, "MM/dd/yyyy hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
From The "HH" Custom Format Specifier
The "HH" custom format specifier (plus any number of additional "H"
specifiers) represents the hour as a number from 00 through 23; that
is, the hour is represented by a zero-based 24-hour clock that counts
the hours since midnight.
So, using 24 as an hour is invalid on this case.
Try with hh format with 00 instead like;
string S = "08/18/2013 00:00:00";
DateTime DT = DateTime.ParseExact(S, "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
Here a DEMO.
If you really want to use 24:00:00 as a hour, take a look Noda Time which developed by Jon.

DateTime Format like HH:mm 24 Hours without AM/PM

I was searching here about converting a string like "16:20" to a DateTime type without losing the format, I said I dont want to add dd/MM/yyy or seconds or AM/PM, because db just accept this format.
I tried with Cultures yet
Thanks in Advance
Just give a date format to your dateTime.
string DateFormat = "yyyy MM d " this willl give you the year month and day. after continuing;
string DateFormat = "yyyy MM d HH:mm:ss " in here the Capital H will give you the 24 hours time format and lowerCase "h" will give you the 12 hours time format...
when you give the Dateformat as a string you can do whatever you want with date and time.
string DateFormat = "yyyyMMdHHmmss";
string date = DateTime.Now.ToStrign(DateFormat);
OR
Console.writeline(DateTime.Now.ToStrign(DateFormat));
OUTPUT:
20120823132544
All DateTime objects must have a date and a time.
If you want just the time, use TimeSpan:
TimeSpan span = TimeSpan.Parse("16:20");
If you want a DateTime, add that time to the min value:
TimeSpan span = TimeSpan.Parse("16.20");
DateTime dt = DateTime.MinValue.Add(span);
// will get you 1/1/1900 4:20 PM which can be formatted with .ToString("HH:mm") for 24 hour formatting
DateTime.Now.ToString("hh:mm") - If it's C#.
Oh. Only read the header.
DateTime dt = new DateTime(2008, 12, 11, Convert.ToInt32("16"), Convert.ToInt32("32"), 0);
what do you mean by "losing the format".
if you convert it to a DateTime type, then the DateTime object will have dd/mm/yy and other properties. depending on how you plan to use the object, you can "recover" your original settings, by formatting the string output like this: DT.ToString("HH:mm");
Since you don't stipulate which DBMS you are using, it is hard to know which answer will help you. If you use IBM Informix Dynamic Server, you would simply use the data type 'DATETIME HOUR TO MINUTE', which will record values in the 24 hour clock.
DateTime.Parse("16:20")
I want to address this part of your question:
without losing the format
A database will generally store all datetime values in a standard common format that's not even human readable. If you use a datetime column the original format is destroyed.
However, when you retrieve the value you cast it back to any format you want. If you want HH:mm you can get it.

Categories

Resources