Question 1: Through the parser we get the string "10d 5h." (10 days and 5 hours) It is necessary to convert it and get the time in hours (10 * 24 + 5) and get the number 245. So far the idea is to do through if and replace the letter with the number, but this is like a crutch, not a solution.

Question 2: The number (int) must be converted to days and hours and output via TextView

What will you tell?

  • Ask two questions. - Igor

1 answer 1

For the time in C # meets TimeSpan and you should work with it.

Read the value of:

Objects such as TimeSpan and DateTime (as well as their counterparts) have two methods ( Parse and ParseExact ), which are responsible for the “reading” of time from the String . Parse will be useful when time is running in a standard format (like hh: mm: ss). ParseExact in this regard is more flexible and allows you to customize the "Parsa" format of time.

Use ParseExact :

 var time = TimeSpan.ParseExact("10д 5ч", "d'д 'h'ч'", null); 

Here we split the input data, separating the plain text from the values ​​of time itself. The values ​​themselves are replaced with the format we need. Also, the method requires culture, here you can think yourself whether you need it or not ...

Get the necessary data:

get the time in hours (10 * 24 + 5) and get the number 245

When using the desired data type, we can easily operate this data as we go. In this case, all you need to do is find out the value of the TotalHours property:

 var totalHours = time.TotalHours; 

Reverse conversion:

The number (int) must be converted to days and hours

For this, there are methods such as FromHours() . They accept double value and give TimeSpan :

 var result = TimeSpan.FromHours(totalHours); 

Well, how to deduce, see it for yourself. Commonly used .ToString(); which can also accept a customizable format , so just play around with it and I think you will understand.

So good luck learning C #!

  • did not even know about the existence of TryParse. Thanks for the tip. Yes, I will deal with the conclusion myself) - Bogdan Ilkiv
  • there was another problem. Sometimes a string may contain not "10d 5h" but "2.3m" (2.3 months). I understand you need to do a check through if and in the methods to count the clock? - Bogdan Ilkiv pm
  • @BogdanIlkiv TimeSpan - this is the time (hours, minutes, seconds), the month does not stuff it ... To work with dates, you need to use DateTime. So, yes, you have to do something like if through and parse and lead to different types of data. As an if condition you can use TryParseExact - it returns bool, and you can return a result through out (note: if (TimeSpan.TryParseExact(value, "d'д 'h'ч'", null, out var time)){var totalHours = time.TotalHours; //...} . - EvgeniyZ