Parsing string into Datetime - c#

This may sound really dumb but I'm struggling with some String parsing into some DateTime
This should be pretty easy with DateTime.ParseExact but the thing is I'm not even able to tell what the pattern is.
string[] patterns = new string[] {"dd/MM/yyyy", "ddMMyyyy", "dd/MM/yyyy HH:mm:ss"};
DateTime test = DateTime.ParseExact(DatMEC, patterns, CultureInfo.InvariantCulture,DateTimeStyles.None);
I used to convert my String to DateTime that way, but in a few cases, I'm facing some parsing error.
I logged the String to check the format, and here is what I've got causing the exception :
String dateException="2/1/2004 12:00:00 AM"
I was wondering what was the appropriate pattern for this?
I tried the following :
"dd/MM/yyyy HH:mm:ss aaa"
"d/M/yyyy HH:mm:ss a"
"M/d/yyyy HH:mm:ss a"
"MM/dd/yyyy HH:mm:ss aaa"
But none of them seems to work.
Am I missing something? I even wonder if it's parseable?

You need to use single day and month numbers d and M and use hh specifier instead of HH since it's 12-hour clock time. Also tt specifier for AM designator.
d/M/yyyy hh:mm:ss tt
Further reading:
Custom Date and Time Format Strings

Related

Convert any DateTime format to US DateTime format in C#

I want to convert any DateTime format to US DateTime format i.e.
MM-dd-yyyy HH:mm:ss
I have the server date which can be anything like it can have AM / PM added in the tail too. I have to take care of most possible scenarios.
CodeValidTill = DateTime.ParseExact(dateObject.ToString(), "MM-dd-yyyy HH:mm:ss", culture);
I have also tried below method to cover most of the cases:
public static DateTime ConvertToUSDateFormat(string dateString)
{
string[] formats = {"M/d/yyyy", "MMM dd yyyy", "MM-dd-yyyy HH:mm:ss", "M/d/yyyy hh:mm:ss tt", "MM/dd/yyyy hh:mm:ss tt"};
return DateTime.ParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
}
Is there any way that we can write a generalized method to handle such situation?
I have a number of hard and fast rules for dealing with DateTimes:
Always store, retrieve and transmit the UTC value. You do not want to deal with Timezones. That way lies madness
Avoid storing, retrieving or transmitting them as Strings.
If you can not avoid store/retreive/transmit as string, pick a fixed String Encoding and Format at all ends
If you follow all those rules you can somewhat reasonably work with DateTimes without going mad.
If you can not follow those rules, you should simply call it impossible so you can enforce the rules with a proper rework of the faulty code.
Agree with jdweng. Its a really good idea to store you dates as a DateTime. This object is format independent and can account for special cultural formats.
Example
DateTime thisDate = new DateTime(2018, 1, 29);
Console.WriteLine(thisDate.ToString("d"));
This should display 1/29/2018
More info on DateTime formatting with the "ToString" overloads

How to convert string dd-mm-yyyy h:mm tt to Datetime in c#?

It may be asked many time but still i cannot get the solution for this i have string in format like 24-12-2016 12:24 PM how to convert it into exactly same format like this into to datetime date type so far what i have tried is:
DateTime dt = DateTime.ParseExact(callobj.CallStartTime, "yyyy-MM-dd hh:mm tt", CultureInfo.GetCultureInfo("en-US"));
// String CallStartTimeString = Convert.ToDateTime(callobj.CallStartTime);
var s = dt.ToString("d-M-yyyy hh:mm tt", CultureInfo.InvariantCulture);
DateTime datetimes = DateTime.ParseExact(s, "d-M-yyyy h:mm tt", CultureInfo.InvariantCulture);
In datetimes am getting like this 12-24-2016 12:24 PM but i need to get like this 24-12-2016 12:24 PM how can i do this ? as am new to c# can someone Helpme out Thanks in advance!! In every other question it just left till string but i need to convert it again to datetimeformat and assign to other datetime datatype
Okey, since Jon and Theodoros are quite right with their comments, I try to clear all things if you let me..
It may be asked many time but still i cannot get the solution for this
i have string in format like 24-12-2016 12:24 PM...
Honestly, based on it's name, your CallStartTime property looks like DateTime typed (well, actually it fits better with TimeSpan but that's irrelevant). But if you really sure it is string, I'm still not with you because you can't parse 24-12-2016 12:24 PM string with yyyy-MM-dd hh:mm tt format since they don't match exactly.
how to convert it into exactly same format like this into to datetime
date type
Wait a second... A DateTime does not have any implicit format. It just have date and time values. It's value stored 64-bit dateData field as Ticks (first 62 bits) and DateTimeKind (63 and 64 bits) of it. "Format" concept only applies when you try to get textual (also known as string) representation.
In datetimes am getting like this 12-24-2016 12:24 PM but i need to
get like this 24-12-2016 12:24 PM
Sorry but I don't believe in you. Since your datetimes is a DateTime, even if you look at in debugger, you can't see any time designators with it. Those are can be only part of a string when you get string representation of your datetimes.
A Datetime instance looks like this in debugger;
Since your question is not very clear, there are 2 options;
You have a string as 24-12-2016 12:24 PM and you want to parse it to DateTime.
You have a Datetime and you want to get it's string representation like 24-12-2016 12:24 PM.
If you try to solve first, you just need to use ParseExact with dd-MM-yyyy hh:mm tt format.
string s = "24-12-2016 12:24 PM";
DateTime dt = DateTime.ParseExact(s, "dd-MM-yyyy hh:mm tt",
CultureInfo.GetCultureInfo("en-US"));
If you try to solve second, you just need to use ToString method with proper format and culture settings.
string s = dt.ToString("dd-MM-yyyy hh:mm tt", CultureInfo.GetCultureInfo("en-US"));
Try This
String str = "12-24-2016 12:24 PM";
DateTime dDate = DateTime.Parse(str, CultureInfo.InvariantCulture);
Srring strDayFirst = Format(dDate, "dd/MM/yyyy");

How to parse default git date format in C#

How do you parse the default git format to a DateTime in C#?
As per What is the format for --date parameter of git commit
The default date format from git looks like Mon Jul 3 17:18:43 2006 +0200.
Right now I don't have control over the output, this strings comes from another tool that printed the date and I need to parse it.
I wouldn't parse this to DateTime, I would parse it to DateTimeOffset since it has a UTC offset value inside of it.
Why? Because if you parse it to DateTime, you will get a DateTime as Local and it might generate different results for different machines since they can have timezone offsets of that time.
For example, I'm in Istanbul and we use Eastern European Time which use UTC+02:00. If I run the example of your code with ParseExact method, I will get the 07/03/2006 18:18:43 as a Local time.
Why? Because in 3 July 2006, my timezone was in a daylight saving time which is UTC+03:00. That's why it generates 1 hour forwarded result. That's the part makes it ambiguous when you parse it to DateTime.
string s = "Mon Jul 3 17:18:43 2006 +0200";
DateTimeOffset dto;
if (DateTimeOffset.TryParseExact(s, "ddd MMM d HH:mm:ss yyyy K",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dto))
{
Console.WriteLine(dto);
}
Now, you have a DateTimeOffset as 07/03/2006 17:18:43 +02:00. You can still get the DateTime part with it's .DateTime property but it's Kind will be Unspecified in that case.
But of course, I suggest to use Noda Time instead which can solve most of the DateTime weirdness.
So far the best format string I found is ddd MMM d HH:mm:ss yyyy K.
DateTime date;
DateTime.TryParseExact(
gitDateString,
"ddd MMM d HH:mm:ss yyyy K",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date
);

ParseExact inverse my day and month

my code below throw an exception as invalid date time. the error occur after i publish it to my server. working find at my developing PC
string str = "27-07-2015 6:15 pm";
DateTime dt = Convert.ToDateTime(DateTime.ParseExact(str, "dd-MM-yyyy h:mm tt", null).ToString("dd-MM-yyyy hh:mm tt"));
it takes '27' as month and '7' as day.
what i did to solve the problem:
i already update the datetime format on that server to dd-MM-yyyy
i double checked the capital and small letter of the date time format.
change the 'null' to 'CultureInfo.InvariantCulture'
change 'pm' to 'PM', 'tt' to 'TT'
read through all the resources i could find on google and stackoverflow, nothing's help.
am i missing something here? i know i did... :(
As #Rawling correctly noted, you're parsing the datetime twice: first, using your custom formatting, and second, using the system's default formatting.
This is silly - you already have the DateTime from the ParseExact method:
string str = "27-07-2015 6:15 pm";
var dt = DateTime.ParseExact(str, "dd-MM-yyyy h:mm tt", null);
That's it, you're done. No need to convert to string again, and parse that once more (and even worse, using the same custom formatting to do the ToString, so the subsequent Convert.ToDateTime is bound to fail anywhere that's not the default datetime formatting).
There are a few possibilities;
Let's analyze your DateTime.ParseExact(str, "dd-MM-yyyy h:mm tt", null) part first. This will be parsed your 27-07-2015 6:15 pm string successfully if;
Your CurrentCulture's TimeSeparator is : and
Your CurrentCulture's PMDesignator is PM (not empty string)
If both are okey, you have successfully parsed a DateTime.
After that, you generate it's textual representation with dd-MM-yyyy hh:mm tt format. And that's still depends on your CurrentCulture, your result might have PM or not. For both case, there is no guaranteed to parse your string with Convert.ToDateTime method because it will be parsed your string only if it is a standard date and time format of your CurrentCulture.
On the other side, what you do doesn't make sense to me. You parse your string first, then you generate string representation of it, then you try to parse this string again. Doesn't make sense, right?
I strongly suspect you just need;
string str = "27-07-2015 6:15 pm";
DateTime dt = DateTime.ParseExact(str, "dd-MM-yyyy h:mm tt", CultureInfo.InvariantCulture);

Can not Parse string to DateTime in Windows Phone 7

I am trying to convert the string to DateTime. But I can not convert.
DateTime dt = DateTime.Parse("16/11/2014", CultureInfo.InvariantCulture);
Console.WriteLine("Date==> " + dt);
The error is FormatException.
My input time format is "dd/MM/yyyy".
Please let me any idea to resolve my problem.
Given that you know your input format, you should specify it with `ParseExact:
DateTime dt = DateTime.ParseExact(text, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
I would always recommend being as explicit as you can be about date/time formats. It makes your intention very clear, and avoids the possibility of getting months and days the wrong way round.
As Soner has stated, CultureInfo.InvariantCulture uses MM/dd/yyyy as its short date pattern, as you can validate with:
Console.WriteLine(CultureInfo.InvariantCulture.DateTimeFormat.ShortDatePattern)
As a mild plug, you might want to consider using my Noda Time project for your date/time handling - aside from anything else, that allows you to treat a date as a date, rather than as a date and time...
Because InvariantCulture doesn't have dd/MM/yyyy as a standard date and time format, but it has MM/dd/yyyy as a standard date and time format.
That's why it thinks your string is MM/dd/yyyy format, but since there is no 16 as a month in Gregorian calender, you get FormatException.
Instead of that, you can use DateTime.TryParseExact method to specify exact format like;
string s = "16/11/2014";
DateTime dt;
if(DateTime.TryParseExact(s, "dd/MM/yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
}

Categories

Resources