Question

I'm new to MVC and I encountered a problem and already spent lots of time on it. Hope you could help me.

I want to combine [datetime]dateFrom and [timespan]timeFrom to [datetime]dtFrom. The reason I have to separate them is because I want to create date calender and time picker to pick up date and time.

Now I'm working with MS SQL Server and I can save dateFrom and timeFrom with no problem.

How can I merge dateFrom and timeFrom and save in dtFrom?

Here is my database entity.

[Table("DaylightSavingsDate")]

public class DaylightSavingsDate

{
    [Column("iTimeZoneId")]
    [Key]
    [ForeignKey("Timezone")]
    public virtual short TimeZoneId { get; set; }

    [Column("dtFrom")]
    public virtual DateTime? dtFrom { get; set; }

    [Column("dtTo")]
    public virtual DateTime? dtTo { get; set; }

    [Column("DateFrom")]
    [DataType(DataType.Date)]
    public virtual DateTime dateFrom { get; set; } 

    [Column("TimeFrom")]
    [DataType(DataType.Time)]
    public virtual TimeSpan timeFrom { get; set; } 

    [Column("DateTo")]
    [DataType(DataType.Date)]
    public virtual DateTime dateTo { get; set; }    

    [Column("TimeTo")]
    [DataType(DataType.Time)]
    public virtual TimeSpan timeTo { get; set; }

    public virtual STTimeZone Timezone { get; set; }
}

And here is the edit action in my controller

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "TimeZoneId,dtFrom,dtTo,dateFrom,dateTo,timeFrom,timeTo")] DaylightSavingsDate daylightsavingsdate)
    {

        if (ModelState.IsValid)
        {

            var dateFrom = daylightsavingsdate.dateFrom;
            var timeFrom = daylightsavingsdate.timeFrom;
            var dtFrom = daylightsavingsdate.dtFrom;

            dtFrom = DateTime.Parse(dateFrom.ToString("yyyy-MM-dd ") + (timeFrom.ToString("hh:mm:ss")));

            globalDb.Save(daylightsavingsdate);
            return RedirectToAction("Index");
        }
        ViewBag.TimeZoneId = new SelectList(globalDb.TimeZones, "Id", "Name", daylightsavingsdate.TimeZoneId);
        return View(daylightsavingsdate);
    }

So I tried to parse dateFrom and timeFrom to DateTime to save in dtFrom but the error shows: "Input string was not in a correct format."

Can anyone tell me how to solve this? Really appreciated.

Était-ce utile?

La solution

Take parsing and formatting out of the picture if you can. You already have a DateTime object and a TimeSpan object. If the date was loaded without a time, then it's time is zero (midnight). So just add the TimeSpan and you're done.

DateTime dateFrom = new DateTime(2014,1,1);
TimeSpan timeFrom = new TimeSpan(1,0,0);
DateTime dtFrom = dateFrom + timeFrom;

Console.WriteLine(dateFrom);
Console.WriteLine(timeFrom);
Console.WriteLine(dtFrom);

Output:

1/1/2014 12:00:00 AM
01:00:00
1/1/2014 1:00:00 AM
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top