DateTime ParseExact not working when changing time - c#

I'm having trouble figuring out why my date is parsed correctly until I change the time of the date passed into the parse method.
var parsedDate = DateTime.ParseExact("2016-02-05T07:00:00+00:00", "yyyy-MM-ddThh:mm:ss+00:00", CultureInfo.InvariantCulture);
dateValueToTryParse = parsedDate.ToString("dd/MM/yyyy");
The required result is outputted and I do get 05/02/2016. However, if I change the string passed in to:
2016-02-19T23:59:00+00:00
The output of dateValueToTryParse remains the same and it is not parsed correctly. Am I doing anything particularly wrong with my parsing? I'm confused as the format seems to be exactly the same?

You need to change your incoming format to yyyy-MM-ddTHH:mm:ss+00:00.
The difference is HH. Capital H means 24 hour clock or "military time".
Otherwise, it is trying to parse hour 23 which doesn't exist.
See here for more detailed information on other formats: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

Changing hh to HH specifier can solve your problem but since your string has an UTC offset value, I would prefer to parse it to DateTimeOffset instead of DateTime for consistency.
var dto = DateTimeOffset.ParseExact("2016-02-05T23:00:00+00:00",
"yyyy-MM-ddTHH:mm:sszzz",
CultureInfo.InvariantCulture);
Now, you have a DateTimeOffset as {05.02.2016 23:00:00 +00:00} and you can use it's .DateTime property to get the DateTime value represented by it.
var dateValueToTryParse = dto.DateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
This will generate 05/02/2016 as a result.

Related

convert resulting string datetime to dateTime value

i am fetching datetime value through xml like:
string time = "20150605020247+0000"
I want to convert into datetime value. I tried with DateTime.Parse, ParseExact, Convert.ToDateTime. It's not working, it's returning the error:
string was not recognised as valid datetime
You should use DateTime.ParseExact like this
DateTime theTime = DateTime.ParseExact(time, "ddMMyyyyHHmmss+ffff,CultureInfo.InvariantCulture);
You should be able to use DateTime.ParseExact, since you know the exact format of the string. If we assume it's year, month, day, hour, minute, second, and offset, then you can do something like:
var result = DateTime.ParseExact("20150605020247+0000", "yyyyMMddHHmmsszzz",
CultureInfo.InvariantCulture);
You need to use exact format specifier in your ParseExact method.
DateTime.ParseExact("20150605020247+0000", "yyyyMMddHHmmsszzz", System.Globalization.CultureInfo.InvariantCulture);
Fiddle: https://dotnetfiddle.net/cQJ9hN
EDIT:
Please check the standard DateTime formats used in .NET world: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings plus check the source of your data how exactly are the string dates produced.
However most likely the '+####' part of your string is the local date UTC offset, not the fractions part of the time (as other answers suggest). So parsing the date by using the "yyyyMMddhhmmssffff" would produce wrong results.

Parsing Date Time in C#, Getting wrong output

I am trying to parse the date by using below code
DateTime mydate = DateTime.ParseExact(datetoconvert,"dd/mm/yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
but its output is wrong, the datetoconvert in above code is 30/Mar/2017 but output is 29/Jan/2017
looking forward for your valuable answers...
Lowercase mm means minute, use MM
DateTime mydate = DateTime.ParseExact(datetoconvert,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
If you want to output it as 30/Mar/2017(different topic):
string result = mydate.ToString("dd/MMM/yyyy", CultureInfo.InvariantCulture);
But note that / has a special meaning too(in Parse and ToString). It will be replaced with your current cultures date-separator which seems to be / but fails with a different. You can avoid it by specifying CultureInfo.InvariantCulture or by masking it by wrapping it with apostrophes:
DateTime mydate = DateTime.ParseExact(datetoconvert,"dd'/'MM'/'yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
replace
"dd/mm/yyyy"
with
"dd/MMM/yyyy"
because "Jan" is matched by MMM instead of mm (for minutes)
Reference
"MMM" The abbreviated name of the month.
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
The date format is wrong. try "dd/MM/yyyy" instead of "dd/mm/yyyy"
If you need abbrivated month name, use "dd/MMM/yyyy"

Parse a UTC date string to date in C#

Simple question, I have this string:
string dateString = "7/12/2014 4:42:00 PM";
This is a date string and it's in the UTC timezone.
I need to convert it to a date, so I'm doing the following:
DateTimeOffset dateOffset;
DateTimeOffset.TryParse(dateString, out dateOffset);
DateTime date = dateOffset.UtcDateTime;
The problem:
When I'm parsing the string to date, the code is considering that the dateString is in the Local Timezone of the PC (+3 GMT), and not in the UTC timezone.
So I am getting the following the dateOffset = {7/12/2014 4:42:00 PM +03:00} and thus date = {7/12/2014 1:42:00 PM}
how can I tell him that the date string provided is in the UTC format and not in the local timezone format?
Thanks
how can I tell him that the date string provided is in the UTC format and not in the local timezone format?
Specify a DateTimeStyles value of AssumeUniversal in the call. That tells the parsing code what to do. For example:
// null here means the thread's current culture - adjust it accordingly.
if (DateTimeOffset.TryParse(dateString, null, DateTimeStyles.AssumeUniversal,
out dateOffset))
{
// Valid
}
You should always use the result of TryParse to tell whether or not it's successfully parsed.
If you know the format and the specific culture, I'd personally use DateTimeOffset.TryParseExact. (Well, to be honest I'd use my Noda Time project to start with, but that's a different matter.)
There is another overload of DateTimeOffset.TryParse
DateTimeOffset.TryParse Method (String, IFormatProvider, DateTimeStyles, DateTimeOffset)
which allows you specify DateTimeStyles. One of the DateTimeStyles is AssumeUniversal, which is what you're looking for:
If no time zone is specified in the parsed string, the string is
assumed to denote a UTC. This value cannot be used with AssumeLocal or
RoundtripKind.
Don't know how .Net API provides, but I guess you could probably use ISO8601 format to indicate a UTC timezone before parsing, i.e, first translate 7/12/2014 4:42:00 PM into something 2014-07-02T16:42:00Z, then use try parse using DateTimeOffset

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