3

i have a question about how thetryparseexact method works.

as have assignment where i need to upload the excel data to sql serever. where i need to convert the datetime column in sql from excel. but i dont have standard format column in EXCEL. so using tryparse exact. but how it differentiate the dd and mm in normal string for example : 10/01/2016 how it differentiate it as dd/mm/yyyy or mm/dd/yyyy.

i am using the below link for reference

Reference Link

advance thanks for answers.

2
  • mm stands for minute use MM Commented Mar 30, 2016 at 6:53
  • hi un-lucky thanks for your answer. sorry but my format is MM/dd/yyyy and dd/MM/yyyy but how tryparseexact method differentiate the given sting is in this format. Commented Mar 30, 2016 at 6:55

1 Answer 1

2

I suggest voting for both possible formats and then analyzing the votes cast:

  // collect all the datetime values in the Excel sheet(s)
  String[] data = new String[] { "01/02/2000", "25/08/2007", "09/10/2010" };
  DateTime dt;

  // then analyze them:
  int votesForDayMonth = data
    .Count(item => DateTime.TryParseExact(item, 
                                          "dd/MM/yyyy", 
                                          CultureInfo.InvariantCulture, 
                                          DateTimeStyles.AssumeLocal, 
                                          out dt));

  int votesForMonthDay = data
    .Count(item => DateTime.TryParseExact(item, 
                                          "MM/dd/yyyy", 
                                          CultureInfo.InvariantCulture,
                                          DateTimeStyles.AssumeLocal, 
                                          out dt));

  if (votesForDayMonth == votesForMonthDay) {
    // Ambiguity, unlucky you
  }
  else if (votesForDayMonth >= data.Length) {
    // dd/MM/yyyy order: all data can be parsed as dd/MM/yyyy but not as MM/dd/yyyy
  }
  else if (votesForMonthDay >= data.Length) {
    // MM/dd/yyyy order: all data can be parsed as MM/dd/yyyy but not as dd/MM/yyyy
  }
  else if (votesForDayMonth > votesForMonthDay) {
    // probably dd/MM/yyyy order
  }
  else {
    // probably MM/dd/yyyy order
  }

In many practical cases when you have enough clear data you can find out the format. In the code above it's "dd/MM/yyyy order"

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.