Zo Has
Zo Has

Reputation: 13028

Function to return only date

I have made a function to convert a textbox value to date. I want to store the converted date in a datetime field in my business object with only date and not time like in format(yyyy-MM-dd)

My function is returning date along with time

public static DateTime ExtractDate(string myDate)
{
    DateTime result = DateTime.MinValue;
    if (myDate != null)
    {
        try
        {
            result=DateTime.Parse(myDate, new System.Globalization.CultureInfo("en-CA", true), System.Globalization.DateTimeStyles.AdjustToUniversal).ToString("yyyy-MM-dd");
        }
        catch (Exception)
        {
            throw new ApplicationException("DateTime conversion error");
        }
    }
    return (result.Date);
}

Upvotes: 0

Views: 7732

Answers (4)

CyberK
CyberK

Reputation: 1578

I would change the method and return a string instead of a DateTime, because there is always time attached (therefor also the name DateTIME ;-))

If you return a string, you can do something like:

return DateTime-object.ToString("yyyy/MM/dd");

Good luck!

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500505

Just use:

result = DateTime.Parse(...).Date;

Therre's no need to convert the date/time back to a string first. The resulting DateTime will just be midnight on the relevant date.

I see that you're adjusting to universal time - you need to be aware that that may change the date. Dates are inherently local - i.e. my August 25th may well start at a different time to yours due to time zones. Alternatively, you could parse it as if it were in UTC to start with and treat it that way. You just need to be careful with what you're doing - you could run into problems where midnight doesn't exist on some days in some time zones. (Been there, done that...)

I would also suggest using DateTime.TryParseExact and specifying the input format. In particular, if you only expect users to enter dates, then specify appropriate date formats. Using TryParseExact instead of ParseExact means you don't have to catch an exception to notice that the user hasn't entered a valid date.

EDIT: Just to clarify: .NET doesn't have a type representing "just a date". Noda Time does, but that's not ready for production yet :( Normally you'd just use a DateTime and ignore the time part.

Upvotes: 3

onof
onof

Reputation: 17367

Date property returns a DateTime with time set to "00.00:00". You can not remove time from a DateTime, you can avoid to show it in the GUI using string.Format("d", yourDate).

Upvotes: 0

Will A
Will A

Reputation: 24988

DateTime itself always includes a time, in the case when you're setting it equal to a 'date' then the time will be 00:00:00. When it comes to displaying the string you'll need to use a format string that includes just the date part.

Upvotes: 5

Related Questions