2

I got string like this :

"10:00 AM"

"11:30 AM"

"12:00 AM"

from this stringi I want to know HOUR and Mins and AM / or PM as separate values.

Mark
  • 8,046
  • 15
  • 48
  • 78
patel
  • 635
  • 5
  • 22
  • 40
  • This question is very appreciated and is NOT a duplication of the other one, some users are really mean and just trying to get points and harming other users. Thanks! – Mayer Spitz Jul 14 '21 at 20:36

3 Answers3

3

You can use String.Split(String[], StringSplitOptions) method like;

string s = "10:00 AM";
var array = s.Split(new string[] {":", " "}, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(array[0]); //10
Console.WriteLine(array[1]); //00
Console.WriteLine(array[2]); //AM

Output will be;

10
00
AM

Here a demonstration.

Or better way, you can use Convert.ToDateTime(String) method for your string like;

var dt = Convert.ToDateTime("10:00 AM");
Console.WriteLine(dt.Hour);
Console.WriteLine(dt.Minute);
Console.WriteLine(dt.ToString("tt"), CultureInfo.InvariantCulture);

Output will be;

10
0
AM

Here a demonstration.

EDIT: As andleer mentioned, using DateTime.Parse can a better option.

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • 1
    I think DateTime.Parse is a better option. Convert.ToDateTime will handle a null but return DateTime.MinValue. Both through an SystemFormat exception if that passed value can't be converted / parsed. – andleer Nov 16 '13 at 20:06
  • @andleer You have a point. Thanks. Updated in my answer. – Soner Gönül Nov 16 '13 at 20:11
2

You can parse into a DateTime object like this:

string timeString = "10:00 AM";
DateTime timeObject = DateTime.ParseExact(timeString, "hh:mm tt", null);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
1

You can use Substring() function to get the Part of the String

Syntax: Substring(int startIndex,int length);

Sample1:

String strDate = "10:00 AM";
String HH = strDate.Substring(0, 2);//10
String MM = strDate.Substring(3, 2);//00
String tt= strDate.Substring(6, 2);//AM

Console.WriteLine(HH+":"+MM+" "+tt);

Output: 10:00 AM

You can also use ToString() function get the required part of Time

Sample2:

DateTime myDate = Convert.ToDateTime(strDate);
Console.WriteLine(myDate.ToString("HH"));
Console.WriteLine(myDate.ToString("mm"));
Console.WriteLine(myDate.ToString("tt",System.Globalization.CultureInfo.InvariantCulture));

Output:

10  
00  
AM
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67