Reason for this strange behavior of DateTime? - c#

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?

Your function always returns 12:30 PM (noon) when called with: GetDatetime("AM", "12", "30");
As Eric mentioned the reason you're getting different results might be that the two computers print out dates in a different way.
For example with my settings the result is:
2012-05-03 12:30:00 (half-hour past noon in my computer's format)
With US settings the result is:
5/3/2012 12:30:00 PM (half-hour past noon in US format)
To print the date in the same way on both machines, you can specify a culture info to use for the date formatting:
DateTime dateResult = GetDatetime("AM", "12", "30");
string strResult = dateResult.ToString(System.Globalization.CultureInfo.GetCultureInfo("en-US"));
On all computers strResult will have the following value: 5/3/2012 12:30:00 PM
But most importantly, you should fix your code to get the expected result (12AM should be midnight, not noon).

You can simply use the DateTime.Parse() (msdn link) (or TryParse()) method to do this. Look at following example code:
string[] times = new string[]
{
"00:00 AM"
, "01:00 AM"
, "10:00 AM"
, "12:00 AM"
, "00:00 PM"
, "01:00 PM"
, "10:00 PM"
, "12:00 PM"
};
foreach (var time in times)
{
DateTime date = DateTime.Parse(time);
Console.WriteLine(date);
}
Gives output:
03/05/2012 00:00:00
03/05/2012 01:00:00
03/05/2012 10:00:00
03/05/2012 00:00:00
03/05/2012 12:00:00
03/05/2012 13:00:00
03/05/2012 22:00:00
03/05/2012 12:00:00
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)):
public static DateTime GetDatetime(string ampm, string hour, string minute)
{
return DateTime.Parse(hour + ":" + minute + " " + ampm);
}

Please check the current culture like this:
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-us");
Because in different cultures, dates are written in different formats. e.g. (may the 3rd) = 3/5/2012 or 5/3/2012 and so on
http://msdn.microsoft.com/en-us/library/system.threading.thread.currentculture.aspx

Your machine isnt setup to use 24 hour clock
The server is.
Change that in the usual way and all will be fine :)
How to:
Click Start, and then click Control Panel.
Click Date, Time, Language, and Regional Options, and then click Regional and Language Options.
To change one or more of the individual settings, click Customise.
Got to time tab and the formats are there!

Related

rounding to a specific 12hr timeframe in c#.net

I realize this may have been answered before, and I may just not be searching for the answer properly, so my apologies if this is a duplicate. This is for a c# webform.
I've got a datetime, set to now, and rounded up the nearest 30 minutes:
DateTime dtNow = RoundUp(DateTime.Now, TimeSpan.FromMinutes(30));
I'm splitting the datetime into its component parts, using M:YY tt (no preceding 0 on the month, two digit year, 12 hr am/pm)
DateString = dtNow.ToString("M/dd/yy");
TimeString = dtNow.ToString("h:mm tt");
What I want do to is simple, I want to see if that TimeString falls between 7:00pm and 5:59am, just need to round it to 6:00am of the following day (unless its past midnight, in which case 6:00am of that day).
Can anyone help me out, or at least point out where its already answered?
You should really stick to DateTime. What you want using string will always need to parse again that string into a DateTime to implement your logic.
A simple solution:
public static DateTime GetRoundedDate(DateTime originalDate)
{
if(originalDate.Hour > 19)
return originalDate.Date.AddDays(1).AddHours(6);
else if (originalDate.Hour < 6)
return originalDate.Date.AddHours(6);
return originalDate;
}
So now you may call:
DateTime dtNow = RoundUp(DateTime.Now, TimeSpan.FromMinutes(30));
var rounded = GetRoundedDate(dtNow);
DateString = rounded.ToString("M/dd/yy");
TimeString = rounded.ToString("h:mm tt");
Just look at the time properties on your DateTime object.
if (dtNow.Hour >= 19 || (dtNow is tomorrow && dtNow.Hour <= 7)) {
//do your stuff
}
where "is tomorrow" is something like dtNow.Date == DateTime.Today.AddDays(1)

C# - Compute total hours between 8:00 to 2:00 AND 8:00 to 12:00

Here's my code
DateTime TimeIn = "8:00 AM",
TimeOut="2:00 AM";
double Total;
private void compute()
{
Total = (TimeOut - TimeIn).TotalHours;
}
8:00am to 2:00am should result 18 hours.But mine is resulting -7
Another problem is when i typed 24:00 as time out C# couldn't recognize it as Time.
It works properly when the TimeOout is less than 12:00am. like 11:59pm backwards.
(eg.: 11:30PM - 8:00AM) it computes properly.
Please Help.
Add +24 hours when negative result.
may be this could help you:
string TimeIn= "8:00 AM";
string TimeOut= "2:00 AM";
TimeSpan duration = DateTime.Parse(TimeOut).Subtract(DateTime.Parse(TimeIn));
The way you have declared the datetime Value is wrong. The right way to do it is by converting the string to datetime format
DateTime TimeIn = Convert.ToDateTime("08:00");
DateTime TimeOut = Convert.ToDateTime("02:00");
TimeSpan ts = TimeIn - TimeOut;
If you need the 18 hours span that you're looking for you'll have to pass the date value as well while assigning data to the variables

How to split string value using c# asp.net

I want to split this 2015-08-11 10:59:41.830 value which is in datetime datatype format and convert it to the following format using c# asp.net.
August 11, 45 minutes ago
The given datetime(i.e-2015-08-11 10:59:41.830) will compare with the current datetime and display like the above format.Please help me to do this.
You will need to parse your date using DateTime.Parse(string s) and once you have that, you take the current date (DateTime.Now) and subtract from it the parsed date.
This should yield a TimeSpan struct. Assuming that both of the dates will refer to the same date, you can then construct your string by taking the pieces you need from the parsed date (Day and Month) and from the time span (Hours, minutes and seconds).
For your specific format you can try ParseExact() "yyyy-MM-dd HH:mm:ss.fff"
static void Main(string[] args)
{
//Given that previous and and now is the same day
DateTime previous = DateTime.ParseExact("2015-08-18 10:59:41.830", "yyyy-MM-dd HH:mm:ss.fff",
System.Globalization.CultureInfo.InvariantCulture);
DateTime now = DateTime.Now;
double value = now.Subtract(previous).TotalMinutes;
Console.WriteLine(string.Format("{0:MMMM dd}, {1} minutes ago", now, (int)value));
Console.ReadLine();
}
npinti already explained it, here the code part;
string s = "2015-08-18 10:59:41.830";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
var ts = dt - DateTime.Now;
Console.WriteLine("{0}, {1} minutes ago",
dt.ToString("MMMM dd", CultureInfo.InvariantCulture),
ts.Minutes);
}
I run this code 2015-08-18 09:50 in my local time and it's generate August 18, 9 minutes ago as a result.
Remember, Minutes property represents minute component of the TimeSpan object and it's range is from -59 to 59. If you wanna get all minutes based on TimeSpan object value, you can use TotalMinutes property (or even as (int)ts.TotalMinutes).
You need this
var yourString = "2015-08-11 10:59:41.830";
var oldDate = DateTime.ParseExact(yourString, "yyyy-MM-dd hh:mm:ss.fff", CultureInfo.InvariantCulture);
//The above two steps are only for if you have date in `string` type, but if you have date in `DateTime` format then skip these.
var difference = DateTime.Now - oldDate;
//here old date is parsed from string or your date in `DateTime` format
var result = string.Format("{0:MMMM dd}, {1} minutes ago", oldDate, difference.Minutes);

C# 12 hour time difference with integers

I have 14 textboxes that takes a user’s input of two times in a 24 hour clock format. When the calculate button is clicked the difference between the two times is calculated and returns the time in decimal format to the respective label. Ideally I would like the user to simply enter time as an integer, such as 1253 or 925 and select AM or PM from the drop down box. Say a user enters 1115 as the in time with AM selected then enters 300 as the out time with PM selected (as shown in the example entry below), the calculate button is clicked and 3.75 is returned in the label.
I have this code below and it works but I get errors when there aren’t exactly four characters. First question, how do I fix this so if an integer such as 800 will be read as 8:00 and not error out?
DateTime dt = DateTime.ParseExact(MondayW1InTextBox.Text, "HHmm", CultureInfo.InvariantCulture);
string timestring = dt.ToString("h:mm");
MondayW1Label.Text = timestring;
Second, once the string is formatted to 12 hour format, how can I get it to take the AM/PM drop down list as an argument for calculating the difference?
Below is the current C# code behind for just the Monday textboxes calculation which is just 24 hour time format, but want to move away from 24 hour time.
protected void CalculateButton_Click(object sender, EventArgs e)
{
TimeSpan TimeIn, TimeOut;
if (!TimeSpan.TryParse(MondayW1InTextBox.Text, out TimeIn)) TimeIn = default(TimeSpan);
if (!TimeSpan.TryParse(MondayW1OutTextBox.Text, out TimeOut)) TimeOut = default(TimeSpan);
MondayW1Label.Text = (TimeOut - TimeIn).TotalHours.ToString("f2");
}
Your first problem is related to the pattern you are using to parse the time: ParseExact will always try to match the exact pattern (in your case, "HHmm") to the string being parsed. That means it expects two digits representing the hours and two digits for the minutes. You can easily make it work if you append a leading zero to your string whenever its size is < 4. You can use the PadLeft method for doing that:
DateTime dt = DateTime.ParseExact(MondayW1InTextBox.Text.PadLeft(4, '0'), "HHmm", CultureInfo.InvariantCulture);
The first argument of PadLeft is the total length of the resulting string (in our case, 4), and the second argument is the character that should be used to fill in ('0').
For your second problem, you can parse the strings to get the DateTime object and, if the PM value is selected, just add 12 hours to the corresponding time.
DateTime timeIn = DateTime.ParseExact(MondayW1InTextBox.Text.PadLeft(4, '0'), "HHmm", CultureInfo.InvariantCulture);
DateTime timeOut = DateTime.ParseExact(MondayW1OutTextBox.Text.PadLeft(4, '0'), "HHmm", CultureInfo.InvariantCulture);
if(dropDownListIn.SelectedValue == "PM") timeIn = timeIn.AddHours(12);
if(dropDownListOut.SelectedValue == "PM") timeOut = timeOut.AddHours(12);
MondayW1Label.Text = (timeOut - timeIn).TotalHours.ToString("f2");
Notice that you can use the subtraction operator on DateTime objects to get the time difference between them, no need to explicitly convert them to TimeSpans.
Maybe this example (it is pretty crude but you get the logic) will be helpful:
string datetime1 = "800";
DateTime dt1 = DateTime.ParseExact((datetime1.Length == 3) ? "0" + datetime1 : datetime1, "hhmm", CultureInfo.InvariantCulture);
string dropDownVal = "AM";
if (dropDownVal == "PM")
dt1 = dt1.AddHours (12);
string datetime2 = "1100";
DateTime dt2 = DateTime.ParseExact((datetime2.Length == 3) ? "0" + datetime2 : datetime2, "hhmm", CultureInfo.InvariantCulture);
dropDownVal = "PM";
if (dropDownVal == "PM")
dt2 = dt2.AddHours (12);
TimeSpan TimeIn, TimeOut;
TimeIn = new TimeSpan (dt1.Ticks);
TimeOut = new TimeSpan(dt2.Ticks);
Console.WriteLine((TimeOut - TimeIn).TotalHours.ToString("f2"));
Console.ReadLine ( );

Convert Full Date and Day

I am wondering if it possible to convert a Full Date and Day e.g.
Thursday 18th of April 2013
to a string (DD/MM/YYYY)
Yes check into Standard Date Time Format strings, and Custom Date Time Format strings
You can try using the DateTime.Parse(string str) method.
For example,
DateTime.Parse("Thu, 18 April 2013");
gives the following output,
04/18/2013 00:00:00
There may be an easier way, but here is a quick method that came to mind based upon my understanding of your question. There is a bit of extra code, so that you can add into a blank Windows form project and see the value.
String strEntry = #"Thursday 18th of April 2013";
DateTime dteValue = DateTime.MinValue;
strEntry = strEntry.Replace("of", null);
strEntry = strEntry.Replace("rd ", " ");
strEntry = strEntry.Replace("th", null);
strEntry = strEntry.Replace("st", null);
DateTime.TryParse(strEntry, out dteValue);
String strFormat = dteValue.ToString("dd/MM/yyyy");
MessageBox.Show(strFormat, "Date Value", MessageBoxButtons.OK);

Categories