There's quite a few different ways to set Date Formats in C#.

How to format dates in ASP.NET?

This post was most recently updated on August 28th, 2019.

Reading Time: 8 minutes.

Have you ever been struggling, to make your ASP.NET MVC views format your properties of type datetime correctly? I have. And I’ve been shot in the leg by weird hacks made by both me (just 6 months earlier) or someone else. .NET Date/DateTime formatting is an endless bag of fun in general.

So I thought I’d finally document the different ways one can set up the formatting of datetime fields in ASP.NET MVC projects specifically. Or at least all the ways I’ve found so far! :)

While this guide has been written for ASP.NET MVC, most of the concepts and the general order of things apply for ASP.NET Core MVC datetime formats as well. Furthermore, a lot of the different methods and layers also apply to datetime formats in any .NET application. And of course, there’s a bunch of tips for date formatting very specific to Entity Framework and even Microsoft SQL Server as well, so you should get some valuable tidbits of info for that tech as well!

Note: This guide does not describe localization on the whole. That’s a wider topic, and a source of endless number of interesting issues :) In this post I only delve on date formatting, and I use TextBox as an example, as it seems to be at the same time the most used component, but also fairly tricky to get right.

Let’s try and figure this out!

Troubleshooting: All the different ways I’ve found to affect the date format of a datetime field in an ASP.NET MVC project

This is the order in which you can set (or mess) up the formatting, starting from the lowest level (database) and ending on the client-side.

I’ve found that for most cases, option 5 (Data Annotations to Model/ViewModel classes) is going to be the best way to go – but even then you need to be aware of the other options, as you (or whoever else working on the same project) can still mess up the formatting on other levels :)

1. Establish a convention and save your dates as preformatted strings already in the database

Yes – people really do that. It’s a bad idea to begin with, but even worse if you’re not consistent with the formats of your stored dates.

Don’t do this. Instead, use datetime column type.

2. Set the column in the database to a certain flavor of datetime

Uh-oh – so just simply using ‘datetime’ doesn’t save us entirely? Well, it almost does. Here are the different date/time formats you can use for your “datetime-ish” columns:

Data typeOutput
time12:35:29. 1234567
date2017-05-08
smalldatetime2017-05-08 12:35:00
datetime2017-05-08 12:35:29.123
datetime22017-05-08 12:35:29. 1234567
datetimeoffset2017-05-08 12:35:29.1234567 +12:15

This will come into effect, if there’s nothing else that affects the format. Usually there is, though, beginning from Entity Framework using DateTime type to store these values.

Source: https://docs.microsoft.com/en-us/sql/t-sql/data-types/datetime-transact-sql?view=sql-server-2017

3. Set up the culture of your service

This is probably the “lowest” level of formatting in your actual application. It’s the easiest way to set your datetime format pretty much everywhere in your application at once.

Setting the culture of the thread your application runs in either in the startup (Configure() in Startup.cs in .NET Core, or Application_Start() in Global.asax.cs in .NET), or in the web.config. See examples below:

How to set the culture of your application in the Application_Start

namespace ...
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
             Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fi-FI");
        }
    }
}

Not too complicated! See below for an alternative approach:

How to set the culture of your application in the web.config

 <system.web>
  <globalization uiCulture="fi" culture="fi"></globalization>
 </system.web>

4. Set up the culture of your page

You can override the culture setting of your whole service or application on a page-to-page basis, if you so desire. The example below shows how to do that!

 <%@ Page UICulture="fi" Culture="fi" %>

5. Add Data Annotations to your EF Model’s classes

For situations when you don’t have to support multiple locales, I think this approach is my favorite. You can specify the format per-field, per-class, in your model, and unless something else is specified on the latter levels, they’ll be used on any views for that particular class. Neat, effective, but granular enough for most uses.

There’s multiple ways you can try and annotate the format directly on your model.

Note, however, that if you’re using automatically generated Model classes (this is the case if your project is database-first, for example), your changes will be overwritten when you next (auto-) update the Model. If this sentence rings no bells and you have no idea what I’m talking about, just check out your .cs -files for your Model classes for something like this in the beginning of the file. This particular warning has been added by EF.

A warning for auto-generated code in Visual Studio ASP.NET MVC Model class
A warning for auto-generated code in Visual Studio ASP.NET MVC Model class

If there’s a comment like that in your classes, it means you should not modify them. They’ll be overwritten if you ever need to recreate them from the database.

In this case, you need to use ViewModels for the annotations.

Using ViewModels instead of Models might be a good idea just in general. Why? They kind of offer you a new level between the Model and View – to offer a dedicated place for some simple logic and formatting, or to add new fields that don’t actually go to database (but are rather used for calculated values) instead of cluttering the Model or Controller (or, heavens forbid, the VIEW) with this code.

Now, the different options you have, are at least these:

Add a DisplayFormat

Example:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy/MM/dd}"] 
public DateTime YourDate { get; set; }

If you want to avoid splitting your date formatting (or whatever else) logic in a million places, you could set the value of DataFormatString to a constant, and use the same value globally.

Override the underlying DataType in the model directly

Okay – a slightly different approach. This way you’ll be able to force the formatting of this DateTime object to be just Date. It’ll still be formatted based on other matters, but it’ll be formatted as a Date, not DateTime.

[DataType(DataType.Date)]
public DateTime YourDate { get; set; }

However, if you need to support multiple locales (or multiple date formats) for this particular property, this approach is not optimal. See below for more options!

6. Insert the date format on the view directly

Are you using the “TextBoxFor()” -method? If you are, you might find that your formats from the model classes are not applied. Weirdly enough, the TextBoxFor is an odd bird and doesn’t adhere to the same format specified for DateTime that other methods seem to work fine with.

For Html.TextBoxFor() -calls the Data Annotations won’t do the trick. This method doesn’t care about the format specified via data annotations at all.

In these cases you can still set the format in the function call directly. The method below is available for MVC4+, so it should work for any current MVC project.

Html.TextBoxFor(m =&gt; m.YourDate, "{0:d MMM yyyy}")
 
// You can even add additional classes in an overloaded call:
Html.TextBoxFor(m =&gt; m.YourDate, "{0:MM/dd/yyyy}", new { @id="datepicker" })

Or with the following notation:

@Html.TextBoxFor(m =&gt; m.YourDate, "{0:MM/dd/yyyy}")

7. Format the DateTime type’s View directly

I’ll readily admit it – this is kind of a tricky one. I’m not sure if I would recommend this almost ever.

For a while I really hated the developer who did this, but after a bit of consideration, I started hating myself issues since I spent like an hour changing the formatting at all different levels, before realizing they had decided to override it at the View for DateTime directly.

Why? Probably they had ran into issues with formatting, and just decided to brute-force their way out of it. And it worked just fine, until they decided to change the format later, and forgot to change this override, too.

Fun times. So, see below how to do this:

@model DateTime?
@using your.namespace;
 
@if (Model.HasValue)
{
 // This'll get you a fairly American date format
 @Convert.ToDateTime(Model).ToString("MM/dd/yyyy}")
}

For the most of the time, don’t do this.

And for the record, I’m not talking about just using the American time format, although arguably that’s a bad idea as well…

But hardcoding the format in a view overriding the default for DateTime (or any other out-of-the-box type for that matter) is probably confusing, and you’re approaching your issue from the wrong direction. There’s probably an easier way around your problem.

8. JavaScript plug-ins and libraries

Okay – this is such a wide and complicated topic, that it’d probably be worth multiple blog articles on its own.

I’m only going to mention the possibility, that the format of your datetime fields might be overridden by JavaScript finally when displaying them. This might be tricky to figure out. While there are a lot of possibilities on how to do this (and equally many ways to mess up), I’m mentioning a couple of examples:

// With jQuery UI DatePicker
$("#yourField").datepicker("option", "dateFormat", "mm/dd/yy");
 
// or another way to do this:
$("#yourField1").datepicker({ dateFormat: 'mm/dd/yy' });
$("#yourField2").datepicker({ dateFormat: 'yy-mm-dd' });
<!-- Another example with BeatPicker library -->
<link rel="stylesheet" href="css/BeatPicker.css">
<script src="js/jquery-2.1.0.min.js"></script>
<script src="js/BeatPicker.js"></script>
 
<input type="text" data-beatpicker="true" data-beatpicker-position="['right','*']" data-beatpicker-format="['DD','MM','YYYY'],separator:'/'">

You might want to search through your code for any JavaScript libraries that affect your date formats. A good idea might be to search for the format that you’re seeing, not for any certain libraries – especially, if you inherited the codebase from someone else, and have no idea which libraries they have chosen to use!

9. Browser settings (by the user or even Group Policies)

Okay – this should be the last level of torment in this particular flavor of Inferno. We’re approaching the end of this rabbit hole.

Like so many other things, Group Policies can affect the date format shown to the end user in your web application.

You can set the desired date format by setting the regional settings using Group Policies. This is a classic problem for Internet Explorer, but you can apply the policies to Google Chrome, too:

https://community.spiceworks.com/topic/595935-change-date-format-using-gpo

Although that appears to be pretty inconsistent (generally, just making it more complicated):

https://community.spiceworks.com/topic/264245-set-default-google-chrome-locale-using-group-policy

I don’t think this is done very often, but at the same time you might still run into this – some organizations absolutely love Group Policies. In my career, I’ve only run into this once.

Afterword

This article described all the different ways I’ve found to affect the formatting of ASP.NET MVC DateTime fields. There’s probably more, and I’ll update them as soon as I run into them :)

Have you found another way? Share it with me in the comments below!

References

These are the sources I went through:

Antti K. Koskela

Antti Koskela is a proud digital native nomadic millennial full stack developer (is that enough funny buzzwords? That's definitely enough funny buzzwords!), who works as a Solutions Architect for Valo Intranet, the product that will make you fall in love with your intranet. Working with the global partner network, he's responsible for the success of Valo deployments happening all around the world.

He's been a developer from 2004 (starting with PHP and Java), and he's been bending and twisting SharePoint into different shapes since MOSS. Nowadays he's not only working on SharePoint, but also on .NET projects, Azure, Office 365 and a lot of other stuff.

This is his personal professional (e.g. professional, but definitely personal) blog.
mm

Leave a Reply

avatar
5000
  Subscribe  
Notify of