Matt Wilko
Matt Wilko

Reputation: 27342

How can I format a non date value as a date value

I am creating a custom type DateOnly which is effectively a DateTime with the Time portion removed.

I have run into a small problem where I want to format the Value of my new type like a date:

Dim startDate As New DateOnly(2012, 1, 2)
Debug.WriteLine(String.Format("{0:ddd}", startDate))

This outputs: 02/01/2012, I want to be able to format this to be Mon

Note: I haven't included any of my code for the DateOnly type (to keep things simple) but I can add it if requested

Upvotes: 1

Views: 141

Answers (2)

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26737

works for me (C#):

  DateTime date = new DateTime(2012, 1, 2);
  var dateString = String.Format("{0:ddd}", date); //Mon

anyway what about the below:

 DateTime date = new DateTime(2012, 1, 2);
 var dayName= date.DayOfWeek.ToString();

if DateOnly is a DateTime you can do :

DateOnly.DayOfWeek.ToString();

for all the culture

System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.DayNames[(int) 
                System.DateTime.Now.DayOfWeek];

more info at http://msdn.microsoft.com/en-us/library/system.datetime.dayofweek.aspx

Upvotes: 1

Matt Wilko
Matt Wilko

Reputation: 27342

I have managed to answer my own problem by implementing IFormattable in my custom type:

Public Overloads Function ToString(fmt As String, provider As IFormatProvider) As String Implements IFormattable.ToString
    Return String.Format("{0:" + fmt + "}", _dateValue)
End Function

This seems to do the trick.

Upvotes: 4

Related Questions