DateTime c# parsing - c#

I try to parse DateTime.TryParse("30-05-2010"), and it throws an exception because it accepts MMddyyyy, and I need ddMMyyyy format. how can I change TryParse format?
thanks,
Dani

You can use the DateTime.TryParseExact method instead which allows you to specify the exact format the string is in

If you're making that adjustment because of local usage, try this:
bool success = DateTime.TryParse("30-05-2010", out dt);
Console.Write(success); // false
// use French rules...
success = DateTime.TryParse("30-05-2010", new CultureInfo("fr-FR"),
System.Globalization.DateTimeStyles.AssumeLocal, out dt);
Console.Write(success); // true

maybe you can use the overload with the formatprovider.
DateTime.TryParse("30-05-2010", <IFormatProvider>)
not sure how to correctly implement it, cant test anything here, but here's more info about the iformatprovider:
http://msdn.microsoft.com/en-us/library/system.iformatprovider.aspx

Related

Formatting DateTime - ignore culture

I need to format a date to the following format:
M-d-yyyy
I tried using:
string.Format("{0:M-d-yyyy}", DateTime.Now)
But the output string will depend on the CurrentCulture on the computer where it's run, so sometimes the output might be 07/09/2014 or 07.09.2014 instead of 09-07-2014.
How can I easily prevent it from converting it based on the culture and treating it as a literal string?
Use CultureInfo.InvariantCulture as the culture or provider argument.
String.Format(CultureInfo.InvariantCulture, "{0:M-d-yyyy}", DateTime.Now)
Use CultureInfo.InvariantCulture as an IFormatProvider parameter:
DateTime.Now.ToString("M-d-yyyy", CultureInfo.InvariantCulture);
You can set the culture of your program with this:
Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;`
You can also use a specific culture if you want (I think en-US is the one you need)
Use the following:
DateTime.Now.ToString("d", DateTimeFormatInfo.InvariantInfo);
or apply other formatting specs as detailed in http://msdn.microsoft.com/en-us/library/az4se3k1%28v=vs.110%29.aspx
Pertinent to your case it could be written as:
DateTime.Now.ToString("M-d-yyyy", DateTimeFormatInfo.InvariantInfo);
Regards,
You can use the .ToString() method on the DateTime object to format it however you'd like. Your code would look something like this:
DateTime.Now.ToString("M-d-yyyy");
More info on formatting date times can be found on the MSDN: http://msdn.microsoft.com/en-us/library/zdtaw1bw%28v=vs.110%29.aspx
you can try
date.ToString("MM/dd/yy", yyyymmddFormat);
or
try whats in this link
http://social.msdn.microsoft.com/Forums/en-US/af4f5a1e-f81d-47fe-981d-818e785b8847/convert-string-to-datetime-object
you can force the string into a standard format if you like

Exception on DateTime Conversion

I'm trying to format a list of datetime. One date is in the format same as what i provided but the factors are not in place. That line of code is given below. Can someone tell me how to skip the error for the below line?
Convert.ToDateTime("22-01-2013 00:00:00").ToString("yyyy-MM-dd");
I would avoid using Convert.ToDateTime to start with. I would suggest using DateTime.TryParse or (preferrably) DateTime.TryParseExact. Both of these will return a value indicating whether the conversion succeeded, so you don't need to start catching exceptions in order to skip bad data. For example:
DateTime parsed;
if (DateTime.TryParse(text, out parsed))
{
string reformatted = parsed.ToString("yyyy-MM-dd");
// Use reformatted
}
else
{
// Log error, perhaps?
}
If you have multiple possible formats, you should consider using the overload of TryParseExact which allows you to specify multiple formats in a single call.
As well as the format, you should consider the culture you want to use. In the above code (and your code) it will use the executing thread's culture. Is that always what you want? The culture can affect all kinds of things - usually if you're specifying a custom format, you want to use the invariant culture. Otherwise you could end up using a non-Gregorian calendar unexpectedly, for example...
EDIT: If your input is always in the format dd-MM-yyyy, then you should probably use:
DateTime parsed;
if (DateTime.TryParseExact(text, "dd-MM-yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.Default, out parsed))
{
string reformatted = parsed.ToString(CultureInfo.InvariantCulture,
"yyyy-MM-dd");
// Use reformatted
}
else
{
// Log error, perhaps?
}
Instead of Convert.ToDateTime use DateTime.Parse or DateTime.ParseExact
ParseExact gives you more control over the format, so for example:
DateTime.ParseExact("22-01-2013 00:00:00","dd-MM-yyyy HH:mm:ss",CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
There is also a TryParseExact variant, which allows you to gracefully handle parse errors.
Try with:
DateTime.ParseExact("22-01-2013 00:00:00","dd-MM-yyyy HH:mm:ss",CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
This way you can specify the exact format for your date-string.
Try to use DateTime.ParseExact() method instead of.
Converts the specified string representation of a date and time to its
DateTime equivalent.
public static void Main(string[] args)
{
Console.WriteLine(DateTime.ParseExact("22-01-2013 00:00:00", "dd-MM-yyyy HH:mm:ss", CultureInfo.CurrentCulture).ToString("yyyy-MM-dd"));
}
Here is a DEMO.
Also check out Coding Best Practices Using DateTime in the .NET Framework which I think every .NET developer should read.

Checking if valid date in C# not working properly

I am using the following function to determine whether input string is valid date or not.
public static bool IsDate(string date)
{
DateTime Temp;
if (DateTime.TryParse(date, out Temp))
return true;
else
return false;
}
Problem is when I give input "1997-09" then it returns true. I want it to check complete date like "1997-08-12"
And no there is no fix date format. Input could also be "19-Feb-2012"
And no there is no fix date format. Input could also be "19-Feb-2012"
There must be, otherwise it's nonesense. If you haven't defined how your system must behave you'd better stop coding and take a moment to define it.
You could use the TryParseExact method which allows you to specify one or more formats you would like to handle.
one easy condition you can add:
public static bool IsDate(string date)
{
DateTime Temp;
return(DateTime.TryParse(date, out Temp)&&date.Length>=10)
}
You should establish list of a correct date formats and then check with DateTime.TryParseExact, something like this:
string format = "yyyy-MM-dd";
DateTime dateTime;
if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
DateTimeStyles.None, out dateTime))
Use DateTime.TryParse, you can specify the format then, more here. http://msdn.microsoft.com/en-us/library/9h21f14e.aspx
To resolve this you should define a datetime-format in your applicaiton.
On any webpage you go, if you see a compilation form, you probabbly will will see some date field too, and near it something like:
DD-MM-YYYY, or MM/DD/YY, or somethign else .
Define for your application format, make it esplicit for the user and check on correctness according to your format.
Just an hypothetic example:
say user inserted a date and you store it into the string like DD-MM-YYYY, one of possible choice could be simply say :
if(dateTimeUserString.Split('-').Length < 3)
//not valid string !
I repeat, this is just an example you should choose more appropriate way for your application.
DateTime.TryParse does have an overload that takes an IFormatProvider to allow specification of custom formats. You may need to define multiple IFormatPrividers to check the various strings you may expect as valid.
Also, rather than the if/else, you could also shorten your code a bit by
return DateTime.TryParse(date, out Temp);
You can return result of parsing directly:
public static bool IsDate(string value)
{
DateTime date;
return DateTime.TryParse(value, out date);
}
And it works with formats you have provided (at least when current culture "en-US").
Your code will run just fine and check the given date string if it can be a valid date using all of the current culture's date formats including this 19-Feb-2012 or 1997-09 of yours or even 19 february.
This makes you flexible in date input.
But if flexibility is not what your are looking for then try to parse for one or more specific formats using TryParseExact.

C# String to DateTime

DateTime frm_datestart = DateTime.Parse(dateStart.Text);
This line throws the error:
Exception Details:
System.FormatException: String was not
recognized as a valid DateTime.
Where the entered string is from Jquery-UI, examples:
09/29/2010
09/30/2010
Anyone know what the correct format should be? I'm suprised this isn't working :S
You can use an overloaded version of the DateTime.Parse() method which accepts a second DateTimeFormatInfo parameter.
System.Globalization.DateTimeFormatInfo dti = new System.Globalization.DateTimeFormatInfo();
dti.ShortDatePattern = "MM/dd/yyyy";
DateTime dt = DateTime.Parse(dateStart.Text, dti);
look for DateTime.ParseExact method.
val = dateStart.Text.ToString("yyyy-M-d HH:mm:ss");
Use DateTime.ParseExact to specify format like this: DateTime.Parse("dd/MM/yyyy", dateStart.Text, null)
The problem with DateTime.ParseExact() method suggested in previous answers is, it fails on some Cultures. So your application may fail to run correctly on certain Operating Systems.
If you are sure that dateStart.Text will always be in the same format (i.e. en-US), you may try passing appropriate CultureInfo as a second argument. For format "MM/dd/yyyy" use CultureInfo.InvariantCulture.

date from string help. I can convert to the string I want, but I can't convert back

I have a string I need to convert back to a date. I can call .ToString("yyyyMMdd") and get the string i want. My question is how can I convert that back into a date? I'm trying something like the following with no luck.
DateTime d;
var formatInfo = new DateTimeFormatInfo {ShortDatePattern = "yyyyMMdd"};
if (DateTime.TryParse(details.DetectionTime.Date, formatInfo, DateTimeStyles.None, out d))
{
lit.Text = d.ToShortTimeString(); //would like 07/30/2010 as the text
}
I've never used DateTimeFormatInfo before if that isn't obvious. Can someone point me in the right direction. I know I could probably use substring and create a new DateTime(y, m, d) etc... I'm just wondering since c# interpreted .ToString() correctly, if it can't derive a date from the very same string it output.
The reverse of DateTime.ToString("yyyyMMdd") is DateTime.TryParseExact, passing "yyyyMMdd" as a format string.
IFormatProvider is a bit of a red herring. You'll normally pass either :
Thread.CurrentThread.Culture, if you're parsing a date typed by the user, when you should obey the user's date preferences
Or CultureInfo.InvariantCulture, if you're parsing a date provided by a program, when your behaviour shouldn't depend on the preferences the user has set up
Use d.ToString("MM/dd/yyyy")
For more options check out http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx
Edit: Read it wrong
Use DateTime.Parse() to parse the string to a datetime.
http://msdn.microsoft.com/en-us/library/1k1skd40.aspx
You can also use DateTime.TryParse to see if the string is able to convert to a date first.
http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx
Alternatively you can also use Convert.ToDateTime()
If you want the DateTime variable back after sending it to a string, save yourself the trouble and just cache or pass the actual DateTime variable around scopes to wherever you need it later and don't bother converting the text back into a DateTime class..
Sorry I just realized this doesn't answer your request, so what you're looking for is:
DateTime.ParseExact(someDateTime, "the format string you used to .tostring generating the string", null);
Convert.ToDateTime("07/30/2010");
I'm assuming you mean to convert a string to a DateTime format. If so use this:
DateTime yourStringConverted = Convert.ToDateTime( yourString );

Categories