将字符串转换为HH MM SS格式 [英] Convert string to HH MM SS format

查看:183
本文介绍了将字符串转换为HH MM SS格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个时间字符串如下

I have 3 time string as follows

 string s1="9"; 
 string s2= "82";
string s3= "24";



我想添加字符串currtime = s1 + s2 + s3;

但这里s2超过60,意味着分钟是超过60然后自动添加一个小时。

我希望时间如下:


I want to add string currtime= s1+s2+s3;
but here s2 is more than 60 ,means minute is more than 60 then automatically add one hour.
I want time is like follow

string finalTime="10:22:24 AM"



同样我们在excel中使用TIME函数。 = TIME(A1,B1,B3)

我们怎么能在c#中做到这一点。


For the same we use TIME function in excel. "=TIME(A1,B1,B3)"
how can we do this in c#.

推荐答案

这个简单的流程会是这样的。首先单独添加HM ans S.然后首先将60分为秒并将答案添加到分钟中,并将余数作为剩余分钟,然后将分钟与60分开,并将答案添加到小时,并将余数作为分钟保留。

最后你得到所有HM ans S作为答案。

注意:以整数格式执行所有操作
The simple flow will like this.first add H M ans S as individually.then first divide second with 60 and add answer into minute and take remainder as your remain minute then divide minute with 60 and add answer into hour and take remainder as minute remain.
finally you get All H M ans S as answer.
NOTE : do all operation in integer format


基本上有两种方式:

There are basically two ways:
  1. 自己做计算
  2. 使用 TimeSpan [ ^ ]执行计算的对象
  1. Do yourself the computation
  2. Use TimeSpan[^] objects to perform the computation





为了使用这两种方法你必须:

  • 将字符串解析为整数
  • 计算添加
  • 将结果格式化为字符串

  •  string s1 = "9";
                string s2 = "82";
                string s3 = "24";
    
                long seconds = Convert.ToInt64(s3) + Convert.ToInt64(s2) * 60+Convert.ToInt64(s1)*3600;
                DateTime startDateTime = DateTime.Today;
                DateTime date = startDateTime.AddSeconds(seconds);
    Console.WriteLine(date.ToString("hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture));
                Console.ReadKey();


    这篇关于将字符串转换为HH MM SS格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆