简体   繁体   中英

How to convert a string to integer?

In my application, am having a TextBox named "Login" , which stores the login time of an empoloyee. Now I just want to convert this string and store the hours and minutes seperately in 2 different Integer variables. Ex:

Login.text="12:40 PM"; // 12:40 PM is system generated time
int HRS=12;
int MINS=40;

I have tried the following code snippet:

string log = Login.Text;
char[] mychar = {'A','M','P'};
int workhrs = Convert.ToInt32(System.DateTime.Now.ToString("HH"));
int logtime = Convert.ToInt32(log.TrimEnd(mychar));
var dt = DateTime.ParseExact(text,"hh:mm tt",CultureInfo.InvariantCulture);
int h = dt.Hour;
int m = dt.Minute;

You could do it like this with simple splitting:

string s = "12:40 PM";
int HRS= Convert.ToInt32(s.Split(':')[0]);
int MINS= Convert.ToInt32(s.Split(':')[1].Split(' ')[0]);

or you use the DateTime.ParseExact() Method like:

string s = "12:40 PM";
DateTime time = DateTime.ParseExact(s,"hh:mm tt",CultureInfo.InvariantCulture);
int HRS = time.Hour;
int MINS= time.Minute;
string StringWithNumberIn = "42";
int SomeValue = Convert.ToInt32(StringWithNumberIn);

Alternatively you can use Int32.TryParse which won't throw an exception if the value in the string isn't actually a valid int.

Firstly, how is your string rendered and is it culture invariant?

var myDate = DateTime.Parse(Login.Text);
int HRS = myDate.Hour;
int MINS = myDate.Minute;

You could convert the text to a DateTime object, then extract from there.

DateTime time = DateTime.Parse(Login.Text);
int minute = time.Minute;
int hour = time.Hour;

A common problem with DateTime.Parse() is that people only provide one format, which leads to some not so obvious failures because the example only has one time in it. For instance, in all the previously posted examples the hour was specified as "hh" which works great for the "12" that the original author posted, but fails if the hour is a single digit like "8" (to succeed with "hh" it would have to be "08" instead). If you change to "h" then "8" would be accepted, but then "12" would fail! The answer is to create an array of allowed formats and pass that in to Parse(). The following code will work for most time entries, including military time:

string s = "8:40 PM"; // or from your login box

DateTime time;
string[] formats = {"h:mm tt", "hh:mm tt", "H:mm", "HH:mm"};
if (DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out time))
{
    int HRS = time.Hour;
    int MINS = time.Minute;

    Console.WriteLine("HRS = " + HRS.ToString());
    Console.WriteLine("MINS = " + MINS.ToString());
}
else
{
    Console.WriteLine("Invalid time format!");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM