将数字转换为月份名称的最佳方法
Best approach to convert number to month name
这是一种很常见的情况,通常我们有两种方法:
1 创建一个第一个元素为空的字符串数组,这样我们就可以直接替换
String[] months = { "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; //first empty so we can replace directly
for(int i =1;i <=12;i++)
{
//Do the magic
xval.Add(months[i] );
}
或者我们可以创建没有空元素的相同数组并替换索引减一(这对我来说似乎不太可读)
由于这是一个很常见的用例,是否有更好的选择(可能更具可读性)将月份编号替换为月份名称? (即 1/12/1983 到 1/Dec/1983 等等)
DateTimeFormatInfo class 会有帮助。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
DateTimeFormatInfo dateTimeInfo = new DateTimeFormatInfo();
Console.Write(dateTimeInfo.GetAbbreviatedMonthName(4)); // Display April
Console.ReadKey();
}
}
}
这是一种很常见的情况,通常我们有两种方法: 1 创建一个第一个元素为空的字符串数组,这样我们就可以直接替换
String[] months = { "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; //first empty so we can replace directly
for(int i =1;i <=12;i++)
{
//Do the magic
xval.Add(months[i] );
}
或者我们可以创建没有空元素的相同数组并替换索引减一(这对我来说似乎不太可读)
由于这是一个很常见的用例,是否有更好的选择(可能更具可读性)将月份编号替换为月份名称? (即 1/12/1983 到 1/Dec/1983 等等)
DateTimeFormatInfo class 会有帮助。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
DateTimeFormatInfo dateTimeInfo = new DateTimeFormatInfo();
Console.Write(dateTimeInfo.GetAbbreviatedMonthName(4)); // Display April
Console.ReadKey();
}
}
}