I have this method:
public static DateTime GetDatetime(string ampm, string hour, string minute)
{
int iHour = Convert.ToInt32(hour);
int iMinute = Convert.ToInt32(minute);
if (ampm == "PM" && iHour != 12)
iHour = 12 + iHour;
DateTime dtTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month,
DateTime.Now.Day, iHour, iMinute, 0);
return dtTime;
}
which basically accepts AM/PM and hour and minute and gives DateTime. I give input as
DateTime startTIme = GetDatetime("AM", "12", "30");
I get time correctly as 12:30 in morning on my local machine. However when I run this same method on server I get 12:30 PM. This is driving me nuts. Can anybody help me out? What am I doing wrong?
Update:
My new function is:
public static DateTime GetDatetime(string ampm, string hour, string minute)
{
int iHour = Convert.ToInt32(hour);
int iMinute = Convert.ToInt32(minute);
if (ampm == "PM" && iHour != 12)
iHour = 12 + iHour;
else if (ampm == "AM" && iHour == 12)
iHour = 0;
DateTime dtTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month,
DateTime.Now.Day, iHour, iMinute, 0);
return dtTime;
}
This seem to work fine. Can anybody find any issue in this code?
You can simply use the
DateTime.Parse()(msdn link) (orTryParse()) method to do this. Look at following example code:Gives output:
In your case, just make a string that contains “hour”:”minutes” + “AM” or “PM”. In code that would be (if your input is invalid, the Parse() method throws an exception or else a very weird result)):