开发者

Add 0's to dates where it is missing in c#?

开发者 https://www.devze.com 2023-02-09 23:09 出处:网络
I have a string with a value in the format of dd/mm/yyyy Now I want to compare that to another string and check if they are equal, the other string can have the value of

I have a string with a value in the format of

dd/mm/yyyy

Now I want to compare that to another string and check if they are equal, the other string can have the value of

dd/mm/yyyy

or sometimes when the day is between 1 and 9:

d/mm/yyyy

Sometimes when the month is between 1 and 9:

dd/m/yyyy

So there are a couple of instances where the string isn't equal but the actual date is. First I only saw that in some cases when the day is between 1-9 it doesn't start with a zero so I did:

createdDate = dateField.value.ToStrin开发者_如何学Gog().Substring(0, 10);
createdDate = createdDate.Trim();
if (createdDate.Length == 9)
    createdDate = "0" + createdDate;

but then I saw that it can be the same for month so there must be a better way to check this?


Why not just parse both, one with the format string "dd/MM/yyyy" and one with the format string "d/M/yyyy" and compare the returned DateTime values? After all, the date being represented is the important part, not the string representation, presumably.


You should use DateTime.Parse to convert both values to dates and then compare the dates.

DateTime.Parse("01/01/2001") == DateTime.Parse("1/1/2001")


When it are strings, that represent dates, why don't you try to parse them to a date, and compare the date instances that you become ?

you just have to make sure that you use the correct pattern when parsing.

Check out the DateTime.TryParse method.


I'd parse both dates into DateTimes and then compare them, that way you don't have to worry about different formats in the compare.


First, parse the strings into values of type DateTime (DateTime.ParseExact), then use the standard equality comparer (==) to compare the dates.

0

精彩评论

暂无评论...
验证码 换一张
取 消