0

I have a method for verifying a datetime, it uses tryParse to do so, the problem is in my computer it returns true when validating a date with format dd/mm/yyyy and in another computer with format mm/dd/yyyy it return false.

How can i manage this?

verifiyDate(String date)
   {
       DateTime temp;
       if (DateTime.TryParse(date.Trim(), out temp))
       {
           return true;
       }
       return false;
   }
user3816931
  • 173
  • 3
  • 7
  • 13
  • The problem is that on the other computer i can not change the format because it is a server that i do not own the rights to change the format. – user3816931 Jul 08 '14 at 22:01
  • Umm I don't think it's the computer. You're using a different format. – mclaassen Jul 08 '14 at 22:01
  • 1
    http://stackoverflow.com/questions/4718960/datetime-tryparse-issue-with-dates-of-yyyy-dd-mm-format – andleer Jul 08 '14 at 22:01
  • Generate and verify the date with the same format. It doesn't matter which one. It must be the same. Is that possible in your case? – usr Jul 08 '14 at 22:02
  • possible duplicate of [Need parse dd.MM.yyyy to DateTime using TryParse](http://stackoverflow.com/questions/3967222/need-parse-dd-mm-yyyy-to-datetime-using-tryparse) – CodeCaster Jul 08 '14 at 22:03
  • 1
    Have you tried DateTime.TryParseExact Method: http://msdn.microsoft.com/en-us/library/system.datetime.tryparseexact(v=vs.110).aspx – Pleun Jul 08 '14 at 22:05
  • Are the computers using different languages and then not using same current culture ? You can specify CultureInfo as parameter to force a specific culture. – NicoD Jul 08 '14 at 22:22

1 Answers1

1

You say something like this:

public static DateTime? ConvertToDate( this string s )
{
  const string   requiredFormat = @"dd/MM/yyyy" ;
  DateTimeStyles style          = DateTimeStyles.AllowLeadingWhite
                                | DateTimeStyles.AllowTrailingWhite
                                ;
  DateTime       converted      ;
  bool           parsed         = DateTime.TryParseExact(
                                    s ,
                                    requiredFormat ,
                                    CultureInfo.InvariantCulture ,
                                    style ,
                                    out converted
                                    ) ;
  DateTime?      value          = parsed ? converted : (DateTime?)null ;

  return value ;
}

which should give you a DateTime holding the converted value or null if the value couldn't be converted.

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
  • @user3816931 - That is definitely C# but the style is rather unconventional. It also won't compile but it looks like it might be typed from memory which would explain that. – ChaosPandion Jul 08 '14 at 23:11
  • @ChaosPandion: fixed the typos for you. The layout is designed for human comprehension and to avoid horizontal scrolling, given SO's narrow page width. – Nicholas Carey Jul 08 '14 at 23:26