1

I need to get the time out of this string format I get in the _event.EventText, how can I get it, I believe it has similar topics, but I did not manage to find the right to solve my problem.

This is a text from which I need to extract text and time. ("09:00:00\nText")

enter image description here

I got the text to get it in this way:

  var value = _event.EventText;
  var text = value.Substring(value.LastIndexOf('\n') + 1);

now I need some time, how can I get it?

Mayur Karmur
  • 2,119
  • 14
  • 35
lasta
  • 311
  • 1
  • 6

4 Answers4

2

Just use TimeSpan.Parse, or TimeSpan.TryParse

Converts the specified string representation of a time interval to its TimeSpan equivalent and returns a value that indicates whether the conversion succeeded.

if (TimeSpan.TryParse(text , out var time))
{
    Console.WriteLine(time);
    // yehaa 
}
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
2

I think it would be a better idea to split by newline. By doing so, you can retrieve both parts (before and after the newline):

var myString = "09:00:00\nTekst!";
var split = myString.Split('\n');

var timeSpan = TimeSpan.Parse(split[0]);
var text = split[1];
Console.WriteLine(timeSpan);
Console.WriteLine(text);
0

Try it

var value = _event.EventText;
var text = value.Split('\n')[0]; // 0 Index return the time
Karan
  • 47
  • 4
0

Time string:

string timeString= value.Substring(0,8);

Time:

DateTime dateTime = DateTime.Parse(value.Substring(0,8));

Time format:

string time24 = dateTime.ToString("HH:mm:ss"); //"09:35:37"
string time12 = dateTime.ToString("h:mm:ss tt"); //"9:35:37 AM"
Croos Nilukshan
  • 154
  • 1
  • 14