-1

I have to display date on page in 'MM/DD/YYY hh:mm:ss tt' format. But I am not able to do it. OccuerdDate is DateTime column with nullable.

I tried following but it is giving error:

@DateTime.ParseExact(item.OccuerdDate, "MM/DD/YYY hh:mm:ss tt",
                     CultureInfo.InvariantCulture)

Error:

CultureInfo doesn't exist in current context.

I don't know how can I achieve this functionality.

Dhwani
  • 7,484
  • 17
  • 78
  • 139
  • 1
    I assume you have imported `System.Globalization`? – Daniel B Aug 02 '14 at 08:12
  • Answering your question requires that we know *exactly* what type OccuerdDate is. Also, ParseExact is used for parsing something into a datetime, not printing it out. – J. Steen Aug 02 '14 at 08:20
  • possible duplicate of [How can I format a nullable DateTime with ToString()?](http://stackoverflow.com/questions/1833054/how-can-i-format-a-nullable-datetime-with-tostring) – J. Steen Aug 02 '14 at 08:32

6 Answers6

3

This must work for nullable datetime.

@item.OccuerdDate.Value.ToString("dd/MM/yyyy hh:mm:ss tt"))
Shasvat
  • 258
  • 3
  • 8
1

For a nullable DateTime, you need to use

item.OccuerdDate.Value.ToString("dd/MM/yyyy hh:mm:ss tt")
romanoza
  • 4,775
  • 3
  • 27
  • 44
1

Try following:

string dt =  item.OccuerdDate.HasValue ?  item.OccuerdDate.Value.ToString("MM/dd/yyyy hh:mm:ss tt") : string.Empty;
Hiren Kagrana
  • 912
  • 8
  • 21
  • 1
    You may want to run that through a compiler. You've got a conditional operator that returns two different types (one of which is not compatible with the variable type you're trying to set the value to), and you're calling the property Now as a method on DateTime. – J. Steen Aug 02 '14 at 08:45
0

In order to display date, you don't have to use ParseExact. In converts date in string format into DateTime. You need to use ToString overload:

item.OccuerdDate.Value.ToString("dd/MM/yyyy HH:mm:ss tt"))

Code snippet with nullable handling:

@model SomeModel

/// stuff
@{
    var displayedDate = item.OccuerdDate.HasValue 
               ?  item.OccuerdDate
                      .Value
                      .ToString("dd/MM/yyyy HH:mm:ss tt" /* destination format */)
               : "No date";
}

<label>@displayedDate</label>
0

You need a using directive at the top of your page:

@using System.Globalization

Or, go to Web.config file under your Views folder, find namespaces element and add System.Globalization like this

<add namespace="System.Globalization" />

Then re-start your solution

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0
@($"{item.OccuerdDate:MM/dd/yyyy HH:mm:ss tt}")
Saeid
  • 422
  • 4
  • 9