c# - 正确使用 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 以仅检索月份和年份?
解决方案
字符串只是一个字符序列。它没有“日期”或“时间”语义。因此,尝试将字符序列(例如DataCupom字符串)格式化为某种表示日期或时间的数据类型是行不通的。
在您的情况下,最简单的方法之一可能是使用“/”作为分隔符拆分DataCupom字符串,然后从表示月份和年份的那些部分组装新的所需字符串。
var parts = DataCupom.Split('/');
return $"{parts[1]}:{parts[2]}";
推荐阅读
- reactjs - 在 React 上显示类别名称
- javascript - 将元素移动到数组中的第一个位置
- php - 如果我的数据库是空的,那么如何自动隐藏我的删除按钮
- angular - 如何在 Angular 5 中排列组件/页面?
- javascript - 按钮需要双击显示图像?
- r - R for loop very slow due to repetitively filtering large dataframe
- json - 从 Node js 中的 url 中提取信息并使用它
- c# - Casting the sender of an event to find the value in a Dictionary that fired the event
- c - 使用 gcc 将汇编代码与 C 代码链接的正确方法是什么
- java - 我们有什么方法可以减少死锁的可能性?