DateTime.ParseExact doesn't do what I want it to do

When the .ParseExact () method is used on a DateTime, I always get the same result as the string I am inserting. Here is my code:

    [Authorize(Roles = "Backoffice, Manager")]
    [HttpPost]
    public ActionResult FilmShowCreate(FilmShowViewModel newFilmShow)
    {
        if (ModelState.IsValidField("FilmId") && ModelState.IsValidField("Time"))
        {
            DateTime unformattedDateTime = newFilmShow.Date.Date + newFilmShow.Time.TimeOfDay;
            string dateString = unformattedDateTime.ToString("yyyy-MM-dd HH:mm:ss");
            DateTime dbDate = DateTime.ParseExact(dateString, "yyyy-MM-dd HH:mm:ss", 
                CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.AdjustToUniversal);

            FilmShow filmShow = new FilmShow
            {
                  Film = filmRepository.GetFilm(newFilmShow.FilmId),
                  Cinema = cinemaRepository.GetCinema(newFilmShow.CinemaId),
                  ThreeDimensional = newFilmShow.ThreeDimensional,
                  Date = dbDate,
                  SpecialEvent = newFilmShow.SpecialEvent
            };

            filmShowsRepository.AddShow(filmShow);

            return View("SuccesfullFilmShowCreate");

      

The dateString is formatted well, but it is a string and I need to store it in the database in DateTime format like this "year-month-day hours: minutes: seconds". But for some reason ParseExact doesn't seem to work in my case. The DateTime format I get is "dd-MM-yyyy HH: mm".

+3


source to share


1 answer


It doesn't do what you want, because, well, this function shouldn't do what you describe.

ParseExact

just indicates that the input must match the specified format to use (not throw an exception). It is analogous Parse

to any valid Date / Time format. It has nothing to do with the future format of any string representation of the object DateTime

it creates.

If you want to output to a given format, pass the format string in ToString

before sending that string to the database. Of course, if you are using something like EF, the conversion is done for you and it doesn't matter.



Example:

string myFormattedDateTime = dbDate.ToString("yyyy-MM-dd HH:mm:ss");

      

After reading your question carefully, I understand that you seem to think that DateTime has some kind of "saved" format. Is not. DateTime is simply a collection of numbers that contain the information needed to represent a date and time. The format you are describing only exists in string representations.

+3


source







All Articles