Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello All,

I need to check the string(will be passed as 'YYYYMMDD' e.g. 20170413) is future date or not. I need to make use of TryParseExact for this?

I have used
ParseExact 
currently and it is working fine.

But now I have to use TryParseExact instead.

Can anyone help in this?

Thanks in advance.

What I have tried:

Tried using
ParseExact 
Posted
Updated 13-Apr-17 3:09am
v2
Comments
[no name] 13-Apr-17 8:54am    
If you reread your posting, you would see that it makes no sense. You used TryParseExact and it is working fine but now you have to use TryParseExact instead?
Swati_g1985 13-Apr-17 8:59am    
Sorry for the Typo- I have used ParseExact but now I have to use TryParseExact
[no name] 13-Apr-17 9:02am    
And so what is the problem? Didn't the example code for TryParseExact answer whatever your question actually is?

I guess you have used TryParse and ask how to use TryParseExact.

Read the documentation:
DateTime.TryParseExact Method (String, String, IFormatProvider, DateTimeStyles, DateTime) (System)[^].

The format string for 'YYYYMMDD' will be "yyyyMMdd".
The provider should be CultureInfo.InvariantCulture.
The style should be DateTimeStyles.None.

So use
C#
DateTime dateValue;
bool isValidDate = DateTime.TryParseExact(dateString, 
    "yyyyMMdd", 
    CultureInfo.InvariantCulture, 
    DateTimeStyles.None, 
    out dateValue);
 
Share this answer
 
You should use one of the DateTime methods, such as DateTime.Compare Method (DateTime, DateTime) (System)[^].
 
Share this answer
 
string d = "20170413";
            
// using ParseExact
DateTime dt1 = DateTime.ParseExact(d, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);

// using TryParseExact
DateTime dt2;
if (DateTime.TryParseExact(d, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dt2))
{
    // the conversion worked
}
else
{
    // the conversion failed
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900