user1701856
user1701856

Reputation: 71

Truncate a Date/Time timestamp in C#

I am looking to remove the time stamp from a dateTime field.

int[] projects = {11157, 11138};

protected void compare(System.Data.DataTable dt1, System.Data.DataTable dt2, int[] arr)
{
    differences.Columns.Add("ID", typeof(int));
    differences.Columns.Add("BRS Date", typeof(string));

    foreach (int value in arr)
    {
        DataRow[] result = dt1.Select("ChangeRequestNo = '" + arr +"' OR [GPP ID] = '" + arr + "'");
        string brs = "";
        string srs = "";
        if (result.Length > 1)
        {
            DataRow row1 = result[0];
            DataRow row2 = result[1];
            DateTime row1date = (DateTime)row1[2];
            DateTime row2date = (DateTime)row2[10];

            //Remove the Time stamp on the dateTime 
            //variable coming from the GPP Extract
            //row2date.cast(floor(cast(getdate() as float)) as datetime);

            if (row1date.Equals(row2date))
            {
                // find your Image control in the Row
                //Image image = ((Image)differences.Rows[1].FindControl("img"));
                // set the path of image
                //img.ImageUrl = "path of image";  
                brs = "True";

            }

This question may have been asked but through SQLserver but doesnt work for C# unless I am doing something wrong(most likely):

How can I truncate a datetime in SQL Server?

Basically the value that comes into my variable is "9/12/2008 12:00:00 AM" and I want "9/12/2008". I have used a few variations of the cast operator but with no luck.

CAST(BRSDate AS Date)          ->  Does nothing

CAST(BRSDate AS varchar(11))   ->  2009-05-26 and some dates come out as 0001-01-01

I apologize for the re-post but the solutions I found are not working for me unfortunately =(. Can anyone help?

Upvotes: 0

Views: 2031

Answers (1)

Habib
Habib

Reputation: 223282

DateTime in .Net contains TimeStamp, you can't really truncate that part, you can use Date property which will have a time stamp set to 12:00:00 AM, or you can format your date by getting only Date part and then compare it.

So for your comparison you can use:

if (row1date.Date.Equals(row2date.Date))

Upvotes: 5

Related Questions