读书人

24时制与12时制转换有关问题

发布时间: 2011-12-28 22:45:21 作者: rapoo

24时制与12时制转换问题?
DX门,本人初学C#,语法方面几乎茫然。做到第2章练习题要求24时制与12时制转换,以下是本人写的。编译不过去。还请高手指点。
using System;

namespace timeConvert
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
void To12(char[] str)
{
string result;
result=str.ToString();//字符数组转成字符串,估计错了
Console.WriteLine( "Your enter is:{0} ",str);
if((str[0]- '0 ')*10+(str[1]- '0 ')> 12) //下午时差计算
{
int time=((str[0]- '0 ')*10+(str[1]- '0 '))%12;
result=time.ToString();
for(int i=2;i <str.GetLength();i++)
result+=str[i];
}
Console.WriteLine( "Convert result is:{0} ",result);
}
static void Main(string[] args)
{
Console.WriteLine( "1----24 convert to 12 ");
Console.WriteLine( "2----12 convert to 24 ");
Console.Write( "Please choose: ");
int n=Console.Read();
char[] str=new char[20];
str=System.Console.ReadLine(); //获得输入;如何将其转成字符数组类型?
if(n==1)


To12(str);
else
//To24(str);


}
}
}

由于本题解法较多,为了学习它的语法。本人上面中文标记地方请DX们使用我的方法转。谢谢了!


[解决办法]
不用这么麻烦吧,你输入字符串是什么格式的,转换成DateTime,然后再ToString()或得DateTimeFormat成指定格式就行了

h 以 1 到 12 范围中的一个数字显示指定的 DateTime 的小时数
H 以 0 到 23 范围中的一个数字显示指定的 DateTime 的小时数

参考MSDN中自定义DateTime格式字符串部分

[解决办法]
写了个,试试:

static string ConventTime(string time)
{
if (Convert.ToInt32(time.Substring(0, 2)) > 12)
return Convert.ToString(Convert.ToInt32(time.Substring(0, 2)) - 12) + time.Substring(2, 3) + "PM ";
else
return time + "AM ";
}
static void Main(string[] args)
{
string time = System.DateTime.Now.TimeOfDay.ToString().Substring(0, 5);
Console.WriteLine(ConventTime(time));
}
[解决办法]
修改后代码是这样的。只是编译通过了:
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void To12(string str)
{
string result;
result = str.ToString();//字符数组转成字符串,估计错了
Console.WriteLine( "Your enter is:{0} ", str);
if ((str[0] - '0 ') * 10 + (str[1] - '0 ') > 12) //下午时差计算
{
int time = ((str[0] - '0 ') * 10 + (str[1] - '0 ')) % 12;
result = time.ToString();
for (int i = 2; i < str.Length; i++)
result += str[i];
}
Console.WriteLine( "Convert result is:{0} ", result);
}
static void Main(string[] args)
{
Console.WriteLine( "1----24 convert to 12 ");
Console.WriteLine( "2----12 convert to 24 ");
Console.Write( "Please choose: ");
int n = Console.Read();
string str = System.Console.ReadLine(); //获得输入;如何将其转成字符数组类型?
if (n == 1)
To12(str);
else
To24(str);
}

private static void To24(string str)
{
//throw new Exception( "The method or operation is not implemented. ");
}
}

读书人网 >C#

热点推荐