convert string to date in C# - c#

How can I convert a date in a string to a DateTime type, even when the date does not conform to what the .net library supports.
"dec 2 2009"
"dec 2, 2009"
"dec 2009"
"december 2009"
"dec. 2009"
"dec. 2, 2009"
and so on
is there a library for this?
assume us date format

Try:
MyDateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt", null);
...or whatever the appropriate date format is...
Reference: DateTime.ParseExact

Check out the DateTime.ParseExact at http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx coupled with the custom formats at http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx.
Here's an example:
...
DateTime.TryParseExact(s, "%M %d yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out resultDateTime)
...

if i understand your question
you can try with
ParseExact
E.g : DateTime.ParseExact(sDate, "mm/dd/yyyy", CultureInfo.InvariantCulture);

"even when the date does not conform to what the .net library supports."
"is there a library for this?"
So you want a library, for when the library doesn't support it?
Obviously, people have probably written other date/time string parsers before, but none of them is going to be exhaustive for anything you might ever possibly need - just find something that works with the formats you expect.

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

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))
{
}

DateTime conversion regardless of culture

I have a text string that needs to become a DateTime object:
Feb 10, 2012 at 16:33.29
This text does not change, but the software will run on many different devices with different DateTime formats.
How can I set a custom DateTime parser so that regardless of culture I will get a fully populated DateTimeobject?
parse with CultureInfo.InvariantCulture?
Use ParseExact with a custom format string and the invariant culture:
DateTime date = DateTime.ParseExact(theString, "MMM d', 'yyyy' at 'HH':'mm'.'ss", CultureInfo.InvariantCulture);
Here’s a custom format to match your example:
var dt = DateTime.ParseExact(
"Feb 10, 2012 at 16:33.29",
"MMM d, yyyy 'at' HH:mm.ss",
CultureInfo.InvariantCulture);
One thing has got nothing to do with the other.
DateTime.Parse(value, formatstr) returns a DateTime.
The DateTime does not have a format, unless you want to talk about how it's represented in memory. When you convert it to a string, you generally do it with an implicit or explicit format, once you have it is no longer a datetime...

How would you format DateTime in international format?

The international string representation format is (YYYY-MM-DD HH:MM:SS ±HHMM).
e.g. 2010-06-10 21:21:10 -0400
basically the problem I am having is figuring out how to get the difference from GMT.
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);
String.Format("{0:yyyy-MM-dd HH:mm:ss ????}", dt);
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss zzz");
will output:
2010-06-29 08:25:16 -07:00
string isoFormat = inputDateTime.Format("s");
I would go with ISO format.
And the W3C has also a note on the topic: Date and Time Formats.
These are international standards.
You want to use DateTimeOffset.
I think that is shown in the hours. That -4 is the difference from GMT.
Oh I see, sorry misunderstood the question.
How would you format DateTime in international format?
You can use a custom format specifier (there is no standard formats for ISO standard date/time formats).
the problem I am having is figuring out how to get the difference from GMT.
Parse using one of DateTimeOffset's static methods, and then check the Offset property.
Or if you mean, how to include the offset in the string: use DateTimeOffset with the correct timezone and a custom format specifier.

Convert Actionscript date string

I'd like to convert a bunch of date strings like the following Mon Aug 7 15:32:52 GMT+0900 2007
to
C# datetime objects.
Is there anything built in to the .net framework to do this or will I have to parse the string into date parts?
Many thanks,
You could use:
DateTime.Parse(datestring);
or
DateTime.TryParse(string, IFormatProvider, DateTimeStyles, out DateTime)
Look at the DateTime.Parse method. You can use the DateTimeFormatInfo class as IFormatProvider. There you could specify the format of the date you want to parse.
Im not sure what "date strings like the following" means since seems you forgot to provide a example. But maybe if you try this.
string date = DateTime.Today.ToString("ddd MMM d HH:mm:ss G'M'Tzzz yyyy", CultureInfo.CreateSpecificCulture("en-EN"));
date = date.Remove(date.LastIndexOf(':'), 1);
// Do whatever you want with the date string
// Output looks like Wed Sep 9 00:00:00 GMT+0200 2009
That looks like a simple RFC formatted date, so a straight DateTime.Parse as Ikke said will work and you shouldn't have to provide the format. You can pass a DateTime object as the second argument in the DateTime.TryParse method to see whether it fails or not, as it returns a boolean.

Categories

Resources