Home > database >  Use correctly String.Format - C#
Use correctly String.Format - C#

Time:11-02

I have two objects of type string, where I retrieve a date in dd/MM/yyyy format, I need to format this date I'm getting to show only month and year, in order to use this object in a groupby to group records by month. I'm doing it as follows, retrieving the date in another object to apply the formatting:

//Object where I retrieve the date with dd/MM/yyyy normally
public string DataCupom { get; set; }

//Object where I retrieve the value of DataCupom and I'm trying to apply the formatting
public string DataCupomAgrupadoMes { get { return String.Format("{MM:yyyy}", DataCupom); } 

How can I apply String.Format correctly to retrieve only month and year?

CodePudding user response:

A string is just a sequence of characters. It has no "date" or "time" semantics. Thus, attempting to format a sequence of characters (sucha as the DataCupom string) like it being some data type representing dates or time is not going to work.

In your case, one of the simplest approaches would probably be splitting the DataCupom string using '/' as separator, and then assemble the new required string from those parts of the split which represent month and year.

   var parts = DataCupom.Split('/');
   return $"{parts[1]}:{parts[2]}";

CodePudding user response:

You can try parsing dateString to DateTime and then format.

   DateTime dateTime = DateTime.Parse(dateString);
   dateTime.ToString("MM/yyyy");

CodePudding user response:

String.Format() uses numeric placeholders:

return String.Format("{0:MMyyyy}", DataCupom);

Where the 0 in the format string means to look at the first additional argument position for the value.

You can also use interpolation:

return $"{DataCupom:MMyyyy}";

or a simple ToString() call:

return DataCupom.ToString("MM:yyyy");
  • Related