MVC how to retrieve the current date and time in a view

11,910

Use custom getters and setters on your DateTime property to provide a default of now:

private DateTime? departure;
public DateTime Departure
{
    get { return departure ?? DateTime.Today; }
    set { departure = value; }
}

private DateTime? departureTime;
public DateTime DepartureTime
{
    get { return departureTime ?? DateTime.Now; }
    set { departureTime = value; }
}

private DateTime? arrival;
public DateTime Arrival
{
    get { return arrival ?? DateTime.Today; }
    set { arrival = value; }
}

Alternatively, you can just manually set the values in your action:

public ActionResult Create()
{
    var journey = new Journey
    {
        Departure = DateTime.Today,
        DepartureTime = DateTime.Now,
        Arrival = DateTime.Today
    };

    ViewBag.TrainId = new SelectList(db.Train, "TrainId", "Name");
    return View(journey);
}
Share:
11,910
MarkJClark
Author by

MarkJClark

Updated on June 04, 2022

Comments

  • MarkJClark
    MarkJClark almost 2 years

    I have been looking for a while now and can't seem to find the answer. What I am trying to do is have the current date and the current Time in two fields on a create page. This page will be used for basic journey scheduling.

    What I have so far is my model

    public class Journey
    {
        public int JourneyId { get; set; }
        public string Name { get; set; }
    
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}",ApplyFormatInEditMode = true)]
        public DateTime Departure { get; set; }
        [DataType(DataType.Time)]
        [DisplayFormat(DataFormatString="{0:hh\\:mm}", ApplyFormatInEditMode = true)]
        public TimeSpan DepartureTime { get; set; }
    
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
        public DateTime Arrival { get; set; }
        public string Description { get; set; }
        public int FareId { get; set; }
        public int TrainId { get; set; }
        public virtual FareType FareType { get; set; }        
        public virtual Train Train { get; set; }
    }    
    

    Account Controller

    public class JourneyController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();
        //
        // GET: Journey
        public ActionResult Index()
        {
            return View(db.Journey.ToList());
        }
    
        //
        // GET: Journey/Create
        public ActionResult Create()
        {
            ViewBag.TrainId = new SelectList(db.Train, "TrainId", "Name");
            return View();
        }
    
        // POST: Journey/Create
        [HttpPost]
        public ActionResult Create(Journey model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Journey.Add(model);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                ViewBag.TrainId = new SelectList(db.Train, "TrainId", "Name", model.TrainId);           
                return RedirectToAction("Index");
            }
            catch (DataException)
            {
                ModelState.AddModelError("", "Sorry something went wrong");
            }
            return View(model);
        }
    
            }
    

    And finaly my view

     <div class="form-horizontal">
        <h4>Journey</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>
    
        <div class="form-group">
            @Html.LabelFor(model => model.Departure, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Departure, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Departure, "", new { @class = "text-danger" })
            </div>
        </div>
    
        <div class="form-group">
            @Html.LabelFor(model => model.DepartureTime, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">                
                @Html.EditorFor(model => model.DepartureTime., new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.DepartureTime, "", new { @class = "text-danger" })
            </div>
        </div>
    
        <div class="form-group">
            @Html.LabelFor(model => model.Arrival, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Arrival, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Arrival, "", new { @class = "text-danger" })
            </div>
        </div>
    

    Any help would be great Many thanks