0

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?

2
  • 7
    You have to convert it to a data type that supports that format, like DateTime. String doesn’t understand anything about dates. Or you can just split the string appropriately. Commented Nov 1, 2021 at 16:40
  • Also, you should always specify a specific CultureInfo when doing formatting - or use Exact methods. Commented Nov 1, 2021 at 16:44

3 Answers 3

4

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]}";
Sign up to request clarification or add additional context in comments.

3 Comments

it was exactly what i needed, thanks!
Nice and Simple. 👌
As this in principle would work, I strongly suggest, not to store timestamps as string properties but as DateTime and just apply the required formatting when a string representation of that value is needed. What If you discover, you need to update your date by for instance adding two days?
3

You can try parsing dateString to DateTime and then format.

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

Comments

-1

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");

1 Comment

Does this really work if DateCupom is already a string and not a DateTime (like in OP's question). If yes, starting with what version?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.