Cant parse string to datetime - c#

DateTime startDate = DateTime.ParseExact("2011-05-25 24:00:00", "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
for some reason parsing this string to a datetime does not want to work. I Tried several things already but it just does not want to work. Most of the internet examples do it like this too.
Does someone sees what is wrong?
thanks

"24:00:00" is not a valid time. Should probably be "00:00:00". If you meant the second that comes after 2011-05-25 23:59:59, that would be 2011-05-26 00:00:00.
For more information about valid value ranges for different format specifiers, check Custom Date and Time Format Strings at MSDN.

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.

c# parse date time with timezone

How can we parse date time with time zone.
<TIMESTAMP_UTC>20180523160000</TIMESTAMP_UTC>
<TIMEZONE>UTC+8</TIMEZONE>
this should convert as in 2018-05-24 00:00:00.
I tried couple of things but could not succeed.
I tried the below command but it throws an error.
DateTime.ParseExact("20180523160000+08:00", "yyyyMMddHHmmssZhhmm", System.Globalization.CultureInfo.InvariantCulture)
Do you know how we can parse this with DateTime Parse methods.
You need to use DateTimeOffset.ParseExact
var date = DateTimeOffset.ParseExact("20180523160000+08:00", "yyyyMMddHHmmsszzz", CultureInfo.InvariantCulture);
Try using DateTimeOffset.Parse() instead of DateTime.Parse() as DateTimeOffset stores timezone info.
You can refer to the following MSDN link for more details:
https://msdn.microsoft.com/en-us/library/bb351654(v=vs.110).aspx
You could invert the sign of your timezone and then parse it with
var dateTime = DateTime.ParseExact(
"20180523160000UTC-8",
"yyyyMMddHHmmssUTCz",
CultureInfo.InvariantCulture);
But if this is a good approach is probably questionable.

DateTime ParseExact not working when changing time

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.

Unable to parse date time in C#

I know such questions are in ton here. Please go through once
I have a string coming from textbox having current date e.g. 10/9/2012, my class property is of DateTime? type. I am using Convert.ToDateTime(datetime_string_from_textbox) but it gives me a FormatException. I then tried DateTime.ParseExact(string, format, CultureInfo, DateTimeStyle) as suggested by Jon Skeet here but still it gave me the same exception.
One more thing — my local machine date time format is dd-mm-yyyy. When I switch this to mm/dd/yyyy format the code works fine. So basically , I want to know how to parse a valid datetime string to a DateTime object irrespective of the regional settings, or any settings or any dependency on local machine.
Is this possible?
Update : Code in use
employee.JoiningDate = DateTime.ParseExact(string.Format("{0} 00:00:00", JoiningDate.Text.Trim()), "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);
Existing Problem and Required Solution
My system datetime shows 24-10-2012 (that is, 24th Oct) and I have 10/17/2012 in my text box (that is, 17th Oct) since the text box date is also valid and after deployment again the client datetime format will become unknown so, I want a generic way to parse any valid datetime string irrespective of regional settings. Is this possible?
This should work:
var date = DateTime.ParseExact(str, "M/d/yyyy", CultureInfo.InvariantCulture);
As tested bellow: 
Try formatting your date to international date format using this method:
How would you format DateTime in international format?
Also you can check this for your current culture:
Set Default DateTime Format c#
It totally depends on the machine settings. DateTime.ParseExact(str, "dd/MM/yyyy", CultureInfo.InvariantCulture); will work for British format but it will give format exception on US format. So use format according to your machine settings.
Try the following if it works
var formatInfo = new DateTimeFormatInfo();
formatInfo.ShortDatePattern = "MM/dd/yyyy";
DateTime.Parse(date, formatInfo);

Why won't this string be converted to DateTime?

2/22/2012 3:30:00
Surely that is an acceptable format to be converted to DateTime using Convert.ToDateTime()?
I would personally avoid using Convert.ToDateTime. I generally prefer1 to use DateTime.TryParseExact, specifying the culture and format string you expect - assuming you have an expected format, of course. If you don't, you have to ask yourself bigger questions.
For example:
DateTime value;
if (DateTime.TryParseExact(text, "M/d/yyyy H:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out value))
{
Console.WriteLine("Parsed to {0}", value);
}
else
{
Console.WriteLine("Failed to parse");
}
That's a slightly odd format to start with - normally a 24-hour format would include a leading 0 for the hour, and a 12-hour format would include an am/pm designator.
1 Well, I prefer to use Noda Time, but that's a different matter...
Surely that is an acceptable format to be converted to DateTime using Convert.ToDateTime()?
Surely not. That would be true for some locales but for example I have a fr-FR locale and this is an invalid date. There are no 22 months in the year. Make sure you specify the format when parsing the date. You could use the TryParseExact method for this.
If you got the Information about Year, Month, etc. separately as Integers I would rather use the Constructor of DateTime.
DateTime myDateTime = new DateTime(year, month, day, hour, minute, second);
Usually nothing can go wrong with this...
It should be able to if you supply an IFormatProvider which specifies the culture (e.g. en-US in that case).
var date = Convert.ToDateTime("2/22/2012 3:30:00", CultureInfo.GetCultureInfo("en-US"));
Here is an example on how to use Convert.ToDateTime() which will help you to understand it :
Convert.ToDateTime example
Or You can try by following this example :
Convert String to DateTime
This works just fine for me:
DateTime dt = Convert.ToDateTime("2/22/2012 3:30:00");
Console.WriteLine(dt.ToShortDateString());
Console.WriteLine(dt.ToShortTimeString());
Of course I am not paying attention to localization like Darin suggests

Categories

Resources