Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice: new DateTime() vs DateTime.Parse()

Tags:

c#

datetime

Let's say I am creating an instance of a class object that has both a name and date. Which is considered best practice when setting the date?

var employees = new List<Employee>() 
{ 
    new Employee {Name = "Foo", HireDate = new DateTime(2000, 1, 15)}, 
    new Employee {Name = "Bar", HireDate = new DateTime(2001, 5, 25)}, 
}; 

or

var employees = new List<Employee>() 
{ 
    new Employee {Name = "Foo", HireDate = DateTime.Parse("2000, 1, 15")}, 
    new Employee {Name = "Bar", HireDate = DateTime.Parse("2001, 5, 25")}, 
}; 

I am assuming there really isn't a huge difference, but I am slightly new to C# so I am not sure which is prefered by the majority of C# programmers and why (performance, readability, etc.). Thanks in advance for any insight you can give!

like image 694
aevanko Avatar asked Nov 13 '11 01:11

aevanko


People also ask

How does DateTime parse work?

The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. It tries to parse the input string completely without throwing a FormatException exception.

What is the use of DateTime ParseExact?

ParseExact(String, String, IFormatProvider) Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

What is DateTime object in c#?

C# DateTime is a structure of value Type like int, double etc. It is available in System namespace and present in mscorlib. dll assembly. It implements interfaces like IComparable, IFormattable, IConvertible, ISerializable, IComparable, IEquatable.

How do you parse a date in darts?

The DateTime has a static method parse that accepts a subset of ISO 8601 format, not my case. The DateFormat class lets you define the date pattern to parse. I've created the pattern "EEE, dd MMM yyyy hh:mm a zzz". Using it I get a FormatException: Trying to read a from Mon, 11 Aug 2014 12:53 pm PDT at position 23 .


3 Answers

Prefer new DateTime.

In favor of new, it will allow you to use variables directly:

// clean because the variable is applied directly to the function
int year = 2000;
var date1 = new DateTime(year, 1, 15);
var date1 = new DateTime(year, 7, 3);
var date1 = new DateTime(year, 8, 19);

// kind of gross and prone to errors because it is appended to the string
int day = 23;
var date1 = DateTime.Parse("2001, 5, " + day.ToString());

In argument against Parse, it doesn't detect errors until runtime:

var date1 = new DateTime(200fdsa, 1, 15); // Error on compile
var date2 = DateTime.Parse("2001fdsjf, 5, 25"); // Must run to find the error

DateTime.Parse will always have poorer performance, because it needs to run code that detect errors and converts the string to numeric values. It does this while your program is running.

However - in cases where you must accept string input (e.g. from a text file), you should use the tool built for the job: DateTime.Parse.


If you're interested in simplifying the specification of date/time constants in your code, there is a library that Jon Skeet wrote for that.

It is a bit old and unmaintained, but the specific code (extension methods on integer constants/date and time structures) probably doesn't really need a lot of maintenance.

  • MiscUtil

The source code for those extensions is under MiscUtil\MiscUtil\Extensions\TimeRelated\ (inside the source zip)

It will let you write your date times in a friendlier fashion, yet still give you clean code with similar performance to new DateTime(2012, 11, 13):

DateTime someDateAndTime = 19.June(1976) + 8.Hours();
like image 134
Merlyn Morgan-Graham Avatar answered Oct 04 '22 00:10

Merlyn Morgan-Graham


I suppose this is ultimately subjective, but I cannot conceive of any good reason for using Parse in this situation. Why perform an (inefficient) string parse over a simple constructor that takes the actual component values?

like image 38
Kirk Woll Avatar answered Oct 01 '22 00:10

Kirk Woll


I'd just use new DateTime() in the example you provided. You know exactly what the year/month/day components of the date are. Why create a string and parse it?

like image 24
Daniel Mann Avatar answered Oct 02 '22 00:10

Daniel Mann