如何将字符串转换为时间格式 [英] How to convert string into time format
问题描述
嗨frds,
我想以小时和分钟格式显示时间。我在110中输入小时和分钟表示它自动占用01:10 AM或01:10 PM。我不知道怎么办这个。任何人都帮助我。
谢谢
string str = 110;
var hr = str [ 0 ] < ; = 9 ? 0 + str [ 0 ] :str [ 0 ];
var min = str [ 1 ] + str [ 2 跨度>];
var time = hr + : + min;
未经测试,但请试一试。 :)
-KR
您可以使用正则表达式解决此问题。这种方法的优点是,如果用户输入的数字不是有效时间,则内置验证。
表达式
< pre lang =text> ^((?< hour> [0-9])|(?< hour> [0-1] [0-9]))(?< min> [0-5] ] [0-9])
* ^ 是起始锚点。这意味着正则表达式引擎从字符串的开头开始
* ((?< hour> [0-9])|(?< hour> [0-1] [0-9]))表示0-9之间的单个数字或两个数字,其中第一个数字必须为0或1.
?< hour> 是一个命名组,可以让以后轻松提取部分正则表达式。
* (?< minute> [0-5] [0-9])表示匹配两位数,其中第一位必须在0-5范围内,第二位0-9位于>范围内。 00 - 59.
*
Hi frds,
I want to display the time in hours and minute format. I enter the hour and minute in 110 means it automatically take 01:10 AM or 01:10 PM. I don't Know how can I proceed this. Anyone help me.
Thank You
string str = "110"; var hr = str[0] <= 9 ? "0" + str[0] : str[0] ; var min = str[1] + str[2]; var time = hr + ":" + min;
Not tested, but give it a try. :)
-KR
You can solve this problem with a regular expression. The advantage of this approach is that you get built in validation if the user enters numbers that is not a valid time.
Expression
^((?<hour>[0-9])|(?<hour>[0-1][0-9]))(?<minute>[0-5][0-9])
* ^ is the start anchor. It means that the regex engine starts at the beginning of the string
* ((?<hour>[0-9])|(?<hour>[0-1][0-9])) means either a single digit from 0-9 or two digits where the first has to be 0 or 1.
?<hour> is a named group and makes it easy to extract parts of the regex later.
* (?<minute>[0-5][0-9]) means that two digit will be matched where the first has to be within the range 0-5 and the second 0-9 -> 00 - 59.
*
这篇关于如何将字符串转换为时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!