using System;
class Solution
{
static string timeConversion(string s)
{
return DateTime.Parse(s).ToString("HH:mm");
}
static void Main(string[] args)
{
Console.WriteLine(timeConversion("01:00 PM"));
Console.Read();
}
}
You can use like this:
string date = "";
date = DateTime.ParseExact("01:00 PM" , "h:mm tt", CultureInfo.InvariantCulture).ToString("HH:mm");
h: 12 hours
mm: mins
tt: PM/AM
HH:24 hours
You can use the ParseExact() method to obtain a DateTime object. You can then use the ToString() method of that DateTime object to convert the string to what ever you need as shown here.
Go through following code to convert the DateTime from 12 hrs to 24 hours.
string currentDateString = DateTime.Now.ToString("dd-MMM-yyyy h:mm tt");
DateTime currentDate = Convert.ToDateTime(currentDateString);
Console.WriteLine("String Current Date: " + currentDateString);
Console.WriteLine("Converted Date: " + currentDate.ToString("dd-MMM-yyyy HH:mm"));
Whenever you want the time should be displayed in24 hours use format "HH"
You can refer following link for further details: Custom Date and Time Format Strings
Convert a string to a DateTime, you could try
DateTime timeValue = Convert.ToDateTime("01:00 PM");
Console.WriteLine(timeValue.ToString("HH:mm"));
If you need to convert a string to a DateTime you could try
DateTime dt = DateTime.Parse("01:00 PM"); // No error checking
or (with error checking)
DateTime dt;
bool res = DateTime.TryParse("01:00 PM", out dt);
Variable dt
contains your datetime, so you can write it
dt.ToString("HH:mm");
Last one works for every DateTime var you have, so if you still have a DateTime, you can write it out in this way.
You'll want to become familiar with Custom Date and Time Format Strings.
DateTime localTime = DateTime.Now;
// 24 hour format -- use 'H' or 'HH'
string timeString24Hour = localTime.ToString("HH:mm", CultureInfo.CurrentCulture);
You may use Cultures to parse and format your string, eg
var cultureSource = new CultureInfo("en-US", false);
var cultureDest = new CultureInfo("de-DE", false);
var source = "01:00 pm";
var dt = DateTime.Parse(source, cultureSource);
Console.WriteLine(dt.ToString("t", cultureDest));
This prints 13:00
int hour = your hour value;
int min = your minute value;
String ampm = your am/pm value;
hour = ampm == "AM" ? hour : (hour % 12) + 12; //convert 12-hour time to 24-hour
var dateTime = new DateTime(0,0,0, hour, min, 0);
var timeString = dateTime.ToString("HH:mm");
DateTime dt = DateTime.Parse("01:00 pm"); //Time in string formate
TimeSpan time = new TimeSpan();
time = dt.TimeOfDay;
Console.WriteLine(time);
Result : 13:00:00
Source: Stackoverflow.com