Shanna
Shanna

Reputation: 783

Replacing date in datetime with another date

    string t3 = "01:30 AM";
    txtStartDate.text = "12-Mar-2013";
    DateTime dat1 = DateTime.Parse(txtStartDate.Text);
    DateTime dat2 = (DateTime.ParseExact(t3, "H:mm tt", CultureInfo.InvariantCulture));
    //this gives 5/30/2013 1:30:00 AM 
    // 5/30/2013 is current date

I want to replace current date with dat1 value that is, I want dat2 to have 12/mar/2013 1:30:00:AM

can anyone help me doing this? thanks in advance

Upvotes: 0

Views: 1553

Answers (3)

Deeko
Deeko

Reputation: 1539

Simple addition would work.

DateTime date = DateTime.Parse(txtStartDate.text) + DateTime.ParseExact(t3, "H:mm tt", CultureInfo.InvariantCulture).TimeOfDay;

Upvotes: 1

Casperah
Casperah

Reputation: 4554

Personally I use something like this:

dat2 = new DateTime(dat1.Year, dat1.Month, dat1.Day, dat2.Hour, dat2.Minunte, dat2.Seconds, dat2.Milliseconds);

But I had the challenge that the time was set to something.

Upvotes: 1

Jason
Jason

Reputation: 15931

After parsing the data string dat1 is set to 12:00 midnight, so you can add the TimeOfDay from dat2 to it.

    var t3 = "01:30 AM";
    txtStartDate.text = "12-Mar-2013";
    DateTime dat1 = DateTime.Parse(txtStartDate.text);

    DateTime dat2 = (DateTime.ParseExact(t3, "H:mm tt", CultureInfo.InvariantCulture));

    dat1 = dat1.Add(dat2.TimeOfDay); // <-- added this line

    //this gives 3/12/2013 1:30:00 AM 
    Console.WriteLine(dat1);
    Console.WriteLine(dat2);

Upvotes: 2

Related Questions