Ömer Faruk Arslan
Ömer Faruk Arslan

Reputation: 129

DateTime Format "dd/MM/yyyy" on ASP.NET MVC5

How I can show DateTime like this dd/MM/yyyy?

Here my code

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? kayittarihi { get; set; }

and

@{                          
   var kayittarihi = DateTime.Now.ToString("dd/MM/yyyy");
}

When I do it this way

Here is an example of the date/time format.

Upvotes: 1

Views: 1931

Answers (2)

Ashiquzzaman
Ashiquzzaman

Reputation: 5284

add <globalization culture="en-GB" /> inside of <system.web> </system.web> in your web.config and check. you can also try

Console.WriteLine(DateTime.Now.ToString("dd/MM/yyyy",new CultureInfo("en-GB")));

If you using Entity Framework and store formatted data in sql server then

at first create a data conversion class

   public DateConvention()
    {
        Properties<DateTime>()
            .Where(x => x.GetCustomAttributes(false).OfType<DataTypeAttribute>()
            .Any(a => a.DataType == DataType.Date))
            .Configure(c => c.HasColumnType("date"));

    }

then

public class YourDbContext : DbContext
{
      //Your DbSet

     protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

           //Your modelBuilder

        modelBuilder.Conventions.Add(new DateConvention());
    }
}

Upvotes: 0

Julian
Julian

Reputation: 36830

You need to quote the slash with a single quote like '/'

So dd'/'MM'/'yyyy

This is needed because the / is a meta character in the format string for dates.

The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days

To change the date separator for a particular date and time string, specify the separator character within a literal string delimiter. For example, the custom format string mm'/'dd'/'yyyy produces a result string in which "/" is always used as the date separator.

See MSDN

See this live demo Fiddle

//ko-KR uses dashes for datetime format by default
Console.WriteLine(DateTime.Now.ToString("dd/MM/yyyy",new CultureInfo("ko-KR"))); //21-04-2017
Console.WriteLine(DateTime.Now.ToString("dd'/'MM'/'yyyy",new CultureInfo("ko-KR"))); //21/04/2017

Upvotes: 1

Related Questions