首页 > 解决方案 > 正确使用 String.Format - C#

问题描述

我有两个类型的对象string,我在其中检索 dd/MM/yyyy 格式的日期,我需要格式化这个日期,我只显示月份和年份,以便在 groupby 中使用这个对象来分组记录月。我这样做如下,检索另一个对象中的日期以应用格式:

//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); } 

如何正确应用 String.Format 以仅检索月份和年份?

标签: c#.net

解决方案


字符串只是一个字符序列。它没有“日期”或“时间”语义。因此,尝试将字符序列(例如DataCupom字符串)格式化为某种表示日期或时间的数据类型是行不通的。

在您的情况下,最简单的方法之一可能是使用“/”作为分隔符拆分DataCupom字符串,然后从表示月份和年份的那些部分组装新的所需字符串。

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

推荐阅读