Parse hour and AM/PM value from a string - C# - c#

What would be the most effective way to parse the hour and AM/PM value from a string format like "9:00 PM" in C#?
Pseudocode:
string input = "9:00 PM";
//use algorithm
//end result
int hour = 9;
string AMPM = "PM";

Try this:
string input = "9:00 PM";
DateTime result;
if (!DateTime.TryParse(input, out result))
{
// Handle
}
int hour = result.Hour == 0 ? 12
: result.Hour <= 12 ? result.Hour
: result.Hour - 12;
string AMPM = result.Hour < 12 ? "AM" : "PM";

Try this:
DateTime result;
string input = "9:00 PM";
//use algorithm
if (DateTime.TryParseExact(input, "h:mm tt",
CultureInfo.CurrentCulture,
DateTimeStyles.None, out result))
{
//end result
int hour = result.Hour > 12 ? result.Hour % 12 : result.Hour;
string AMPM = result.ToString("tt");
}

string input = "9:00 PM";
DateTime dt = DateTime.Parse(input);
int hour = int.Parse(dt.ToString("hh"));
string AMPM = dt.ToString("tt");
See Custom Date and Time Format Strings for getting information from a DateTime value in all kinds of formats.

Use DateTime.Parse:
string input = "9:00 PM";
DateTime parsed = DateTime.Parse(input);
int hour = int.Parse(dt.ToString("h"));
string AMPM = parsed.ToString("tt");
Edit: Removed %12 on hour since that fails for 12 AM.

begin pseudocode:
DateTime dt;
if (!DateTime.TryParse("9:00 AM", out dt))
{
//error
}
end pseudocode

Related

How to concatenate integer with string in C#?

I am developing a Console application for converting the time from 12 hours format to 24 hours format:
input: 02:03:34PM expected output:14:03:34
But I am getting 14:3:34
Below is my code snippet:
string[] arr_temp = Console.ReadLine().Split(':');
string time = arr_temp[2].ToUpper().Contains("AM") ? "AM" : "PM";
string sec=string.Empty;
for (int i = 0; i < 2; i++)
{
sec+= arr_temp[2][i];
}
int _hour = Int32.Parse(arr_temp[0])==0?0: Int32.Parse(arr_temp[0]);
int _minute = Int32.Parse(arr_temp[1]) == 0 ? 0 : Int32.Parse(arr_temp[1]);
int _sec = Int32.Parse(sec)==0?0: Int32.Parse(sec);
_hour = (time == "PM") ? _hour += 12 : _hour += 0;
_hour = (_hour < 10) ? '0' + _hour : _hour;
_minute = (_minute < 10) ? '0' + _minute : _minute;
_sec = (_sec < 10) ? '0' + _sec : _sec;
I am not getting the expected output.
Please suggest.
Seems a bit complicated to me as there's a much simpler way to display your DateTime variable to either 12 or 24 hours format.
First you will have to convert your string to a valid DateTime object. There are parsing methods which you can use, but you will have first to validate the input string returned by the user as a valid date.
Use the following code in order to convert your string to DateTime:
string dateString = "03/01/2009 10:00 AM";
DateTime date = DateTime.Parse(dateString);
DateTime.Parse will throw an exception if input string is not in the right format. In order to make sure this doesn't happen, use DateTime.TryParse instead.
string dateString = "03/01/2009 10:00 AM";
DateTime dateTime;
if (DateTime.TryParse(dateString , out dateTime))
{
Console.WriteLine(dateTime);
}
Then you can display the DateTime variable and format it the way you want.
DateTime dateTime = DateTime.Now;
string str12Format = dateTime.ToString("hh:mm:ss tt"); //12 hours format
string str24Format = dateTime.ToString("HH:mm:ss tt"); //24 hours format
_hour in your code is an integer. You cannot concatenate string to an integer. But the reverse is possible.
So you should use this instead :
int _hour = Int32.Parse(arr_temp[0])==0?0: Int32.Parse(arr_temp[0]);
int _minute = Int32.Parse(arr_temp[1]) == 0 ? 0 : Int32.Parse(arr_temp[1]);
int _sec = Int32.Parse(sec)==0?0: Int32.Parse(sec);
_hour = (time == "PM") ? _hour += 12 : _hour += 0;
String _hourS = (_hour < 10) ? '0' + _hour : _hour;
String _minuteS = (_minute < 10) ? '0' + _minute : _minute;
Try using DateTime.TryParseExact followed by ToString, do not repeat Microsoft and reinvent the wheel:
string source = Console.ReadLine();
DateTime date;
// DateTime.TryParseExact supports many formats; that's why "12:34AM" will be accepted
// DateTimeStyles.AllowWhiteSpaces let us be nice and allow, say "11 : 34 : 47 PM"
if (DateTime.TryParseExact(
source,
new string[] {"h:m:stt" , "h:mtt", "htt", "H:m:s", "H:m", "H"},
CultureInfo.InvariantCulture, // or CultureInfo.CurrentCulture
DateTimeStyles.AssumeLocal | DateTimeStyles.AllowWhiteSpaces,
out date))
Console.WriteLine(date.ToString("HH:mm:ss"));
else
Console.WriteLine($"Sorry, {source} is not a valid date");
Just pass you input
public static TimeSpan ConvertToAMPM(DateTime date)
{
return TimeSpan.Parse(date.ToString("h:mm tt",
CultureInfo.InvariantCulture));
}
public static TimeSpan ConvertTo24Hour(string time)
{
var cultureSource = new CultureInfo("en-US", false);
var cultureDest = new CultureInfo("de-DE", false);
var dt = DateTime.Parse(time, cultureSource);
return TimeSpan.Parse(dt.ToString("t", cultureDest));
}
The other answers so far mostly address the example of handling a DateTime, but they do not explain why your code breaks.
What you are trying to do is to add a leading zero to an int variable just as you'd do it with a string.
The problem is that the internal representation of an int is just the number itself, and it carries no format information. As such, it cannot store information about leading zeros. This can only be done by using string, which do not represent a number but a collection of characters.
So the essence is that you need to see the data and its representation as two separate things. In general it's best to keep the data in its native form and only convert it at the very last moment when needed for display. This also allows you to respect cultural differences of the display representation.
Many basic data types (including int and DateTime etc.) are formattable. What this means is that they can be converted to a string (display) representation with respect to a pattern describing how this representation should be. For int, such a pattern can define that it needs to have a leading zero like so:
string _hourDisplay = _hour.ToString("00");
Hi Nishank, Use this code :
string[] arr_temp = Console.ReadLine().Split(':');
string time = arr_temp[2].ToUpper().Contains("AM") ? "AM" : "PM";
string sec = arr_temp[2].Substring(0, 2);
string _hour = "";
if (time == "PM" && Int32.Parse(arr_temp[0]) < 12)
_hour = (Int32.Parse(arr_temp[0]) + 12).ToString("D2");
else if (time == "AM" && Int32.Parse(arr_temp[0]) == 12)
_hour = "00";
else
_hour = Int32.Parse(arr_temp[0]).ToString("D2");
string _minute = Int32.Parse(arr_temp[1]) == 0 ? "00" : Int32.Parse(arr_temp[1]).ToString("D2");
string _sec = Int32.Parse(sec) == 0 ? "00" : Int32.Parse(sec).ToString("D2");
string outputTime = _hour + ":" + _minute + ":" + _sec + "" + time;

How to convert the timestamp from 24 hr format to 12 hr format in C#?

I want to convert to timestamp in 24hrs fromat to 12 hrs format.Here is my code with output mentioned in braces.
date = Dyear + "" + Dmonth + "" + Dday + " " + strhour+""+strminute+""+"00"; (20130628 142900)
DateTime dt = new DateTime(Convert.ToInt32(Dyear), Convert.ToInt32(Dmonth), Convert.ToInt32(Dday), Convert.ToInt32(strhour), Convert.ToInt32(strminute), 00);(6/28/2013 2:29:00 PM)
TimeSpan ts = dt.Subtract(new DateTime(1970, 01, 01, 00, 00, 00));(15884.14:29:00)
String sTimeStamp = ts.TotalMilliseconds.ToString("0"); (1372429740000)
the above sTimeStamp will be in MM/DD/YYYY HH:MM:ttt format(06/28/2013 19:59:000) like "1372429740".
I want to display the time stamp in 12 hr format like MM/DD/YYYY hh:mm:ttt format(06/28/2013 07:59:000) like "1372386540"
Bear in mind that the format you refer is just for displaying purposes. If you want to account for this modification in your calculations (putting 2 instead of 14), a 12h lag would appear.
If you just want to display 6/28/2013 2:29:00, you can use the following string (the calculated miliseconds will not be affected):
string sTimeStamp = dt.ToString("MM/dd/yyyy hh:mm:ss tt");
If what you want is performing this change during the time calculations (not sure about the reason for doing that), you have to modify the way in which dt is generated (this time, the calculated milisenconds will be affected: 12h lag with respect to the option above):
DateTime dt = new DateTime(Convert.ToInt32(Dyear), Convert.ToInt32(Dmonth), Convert.ToInt32(Dday), Convert.ToInt32(new DateTime(2000, 1, 1, Convert.ToInt32(strhour), 0, 0).ToString("hh:mm tt").Split(':')[0]), Convert.ToInt32(strminute), 0);
In this second case, dt will always be formed on account of the "12h understanding" of the input value; for example: it will account for 2(am) if strhour is either 2 or 14.
internal static string ConvertTo_12_Format(string str)
{
//using system function
DateTime dt = DateTime.ParseExact(str, "HH:mm", System.Globalization.CultureInfo.InvariantCulture);
string s = dt.ToString("hh:mm");
//using logic
StringBuilder sb = new StringBuilder();
int h1 = (int)str[0] - '0';
int h2 = (int)str[1] - '0';
string Meridien;
int hh = h1 * 10 + h2;
if (hh < 12)
{
Meridien = "AM";
}
else
Meridien = "PM";
hh %= 12;
int c1 = (int)str[3] - '0';
int c2 = (int)str[4] - '0';
if (hh == 0)
{
sb.Append("12:");
//18:30
// Printing minutes and seconds
sb.Append(c1.ToString() + c2.ToString());
}
else
{
if(hh < 10)
{
sb.Append("0" + hh + ":");
sb.Append(c1.ToString() + c2.ToString());
}else
{
sb.Append(hh + ":");
sb.Append(c1.ToString() + c2.ToString());
}
}
sb.Append(" "+Meridien);
return sb.ToString();
}

Calculate age from date in textbox in C# [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calculating age from birthday
How do you calculate age in years, taking input from TextBox in the format dd/MM/yyyy?
e.g.
input: txtDOB.Text 20/02/1989 (String format)
output: txtAge.Text 23
You can use the Substract method of DateTime (link) and then use the Days property to determine the actual age:
DateTime now = DateTime.Now;
DateTime givenDate = DateTime.Parse(input);
int days = now.Subtract(givenDate).Days
int age = Math.Floor(days / 365.24219)
TimeSpan TS = DateTime.Now - new DateTime(1989, 02, 20);
double Years = TS.TotalDays / 365.25; // 365 1/4 days per year
As already noted in a comment, the correct answer is here: Calculate age in C#
You just need to get the birthday as a DateTime:
DateTime bday = DateTime.ParseExact("20/02/1989", "dd/MM/yyyy", CultureInfo.InvariantCulture);
The following will work once you have parsed the birth date into a DateTime:
static int AgeInYears(DateTime birthday, DateTime today)
{
return ((today.Year - birthday.Year) * 372 + (today.Month - birthday.Month) * 31 + (today.Day - birthday.Day)) / 372;
}
Parse the date like so:
DateTime dob = DateTime.ParseExact("20/02/1989", "dd/MM/yyyy", CultureInfo.InvariantCulture);
And a sample program:
using System;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
DateTime dob = new DateTime(2010, 12, 30);
DateTime today = DateTime.Now;
int age = AgeInYears(dob, today);
Console.WriteLine(age); // Prints "1"
}
static int AgeInYears(DateTime birthday, DateTime today)
{
return ((today.Year - birthday.Year) * 372 + (today.Month - birthday.Month) * 31 + (today.Day - birthday.Day)) / 372;
}
}
}
This answer isn't the most efficient as it uses a loop, but it doesn't rely on using 365.25 magic numbers either.
A function to return the whole number of years from a datetime to today:
public static int CalcYears(DateTime fromDate)
{
int years = 0;
DateTime toDate = DateTime.Now;
while (toDate.AddYears(-1) >= fromDate)
{
years++;
toDate = toDate.AddYears(-1);
}
return years;
}
Usage:
int age = CalcYears(DateTime.ParseExact(txtDateOfBirth.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture));
var date = DateTime.ParseExact("20/02/1989", "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
var age = (DateTime.Today.Year - date.Year);
Console.WriteLine(age);
Try this
string[] AgeVal=textbox.text.split('/');
string Year=AgeVal[2].tostring();
string CurrentYear= DateTime.Now.Date.Year.ToString();
int Age=Convert.ToInt16((Current))-Convert.ToInt16((Year));
Subtract the two values and get your age.

How to Compare DateTime C# Months and weeks

I need to compare a date in C#
if the date is less than 12 months,i need to set a boolean value
My Code is
String d = "26/06/10";
DateTime dt = DateTime.ParseExact(d, "dd/MM/yy", null);
if ((dt > DateTime.Now.AddMonths(-12) ) )
{
Console.WriteLine("It is less than 12 months");
}
else
{
Console.WriteLine("It is more than 12 months");
}
Is the best way to compare date in c#.
similarly i need to compare date is less than two weeks or not
Any help appreciated
Thanks
sup
You could use TimeSpan to get the difference between two DateTime values
String d = "26/06/10";
DateTime dt = DateTime.ParseExact(d, "dd/MM/yy", null);
DateTime dt2 = DateTime.Now.AddMonths(-12);
TimeSpan ts = dt - dt2;
You can use ts.Days to compare
You could do
DateTime date2 = DateTime.Now.AddMonths(-12);
//Or if you want to neglect the time part you could do
DateTime date2 = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,0,0,0).AddMonths(-12);
String d = "26/06/10";
DateTime date1 = DateTime.ParseExact(d, "dd/MM/yy", null);
int result = DateTime.Compare(date1, date2);
string res;
if (result < 0)
Console.WriteLine("It is less than 12 months");
else if (result == 0)
res = "is the equal";
else
Console.WriteLine("It is more than 12 months");
The problem with your code snippet is that it will output "It is more than 12 months" even if the date is equal.
For two weeks:
if (dt1.Subtract(dt2).Days > 14)
{
...
}
For 12 Months(one year) (Considering day of the month is not important):
var monthDifference = ((dt1.Year - dt2.Year) * 12) + dt1.Month - dt2.Month
For a clearer understanding: you do not want to compare two dates (or DateTimes) but two TimeSpans. Namely the difference in time between now and the date you supplied - and the a time span of 12 months.
String d = "26/06/10";
DateTime dt = DateTime.ParseExact(d, "dd/MM/yy", CultureInfo.InvariantCulture);
TimeSpan deltaTimeSpan = dt - DateTime.Now; // get the time difference between now and the time given
TimeSpan twelveMonths = new TimeSpan(365,0,0,0); // get a time span of 12 months
// round the amount of days down and always supply a positive number of days
int deltaTime = Convert.ToInt32(Math.Abs(Math.Floor(deltaTimeSpan.TotalDays)));
if (twelveMonths.TotalDays > deltaTime)
{
Console.WriteLine(string.Format("It is less than 12 months ({0} days).", deltaTime));
}
else if (twelveMonths.TotalDays < deltaTime)
{
Console.WriteLine(string.Format("It is more than 12 months ({0} days).", deltaTime));
}
else
{
Console.WriteLine(string.Format("The difference in time is exactly 12 months. ({0} days).", deltaTime);
}
Take note that this example certainly does not take in account leap years. The code does take in account weather the year to compare with lies in the past or the future (by converting the TimeSpan into a positive value and comparing against that one).
Adjusting the above code to do the same for two weeks or any other time span should be simple enough. Just change the TimeSpan I named "twelveMonths".
DateTime date1 = DateTime.Now.AddMonths(-12)
if(DateTime.Compare(dt, date1 )
{
//provided date is within 12 months
}
else
{
//provided date is after 12 months
}

Calculate difference between two dates (number of days)?

I see that this question has been answered for Java, JavaScript, and PHP, but not C#. So, how might one calculate the number of days between two dates in C#?
Assuming StartDate and EndDate are of type DateTime:
(EndDate - StartDate).TotalDays
The top answer is correct, however if you would like only WHOLE days as an int and are happy to forgo the time component of the date then consider:
(EndDate.Date - StartDate.Date).Days
Again assuming StartDate and EndDate are of type DateTime.
Use TimeSpan object which is the result of date substraction:
DateTime d1;
DateTime d2;
return (d1 - d2).TotalDays;
I think this will do what you want:
DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(-1);
TimeSpan t = d1 - d2;
double NrOfDays = t.TotalDays;
DateTime xmas = new DateTime(2009, 12, 25);
double daysUntilChristmas = xmas.Subtract(DateTime.Today).TotalDays;
// Difference in days, hours, and minutes.
TimeSpan ts = EndDate - StartDate;
// Difference in days.
int differenceInDays = ts.Days; // This is in int
double differenceInDays= ts.TotalDays; // This is in double
// Difference in Hours.
int differenceInHours = ts.Hours; // This is in int
double differenceInHours= ts.TotalHours; // This is in double
// Difference in Minutes.
int differenceInMinutes = ts.Minutes; // This is in int
double differenceInMinutes= ts.TotalMinutes; // This is in double
You can also get the difference in seconds, milliseconds and ticks.
In case someone wants numer of whole days as a double (a, b of type DateTime):
(a.Date - b.Date).TotalDays
There often is a debate on time (hours) when it comes to counting days between two dates. The responses to the question and their comments show no exception.
Considering StartDate and EndDate are of type DateTime: if performance is not a concern, I would strongly recommend documenting your calculation through intermediate conversions. For example, (EndDate - StartDate).Days is unintuitive because rounding will depend on the hour component of StartDate and EndDate.
If you want the duration in days to include fractions of days, then as already suggested
use (EndDate - StartDate).TotalDays.
If you want the duration to reflect
the distance between two days, then use (EndDate.Date - StartDate.Date).Days
If you want the duration to reflect the
duration between the morning of the start date, and the evening of
the end date (what you typically see in project management software), then use
(EndDate.Date - StartDate.Date).Days + 1
You can try this
EndDate.Date.Subtract(DateTime.Now.Date).Days
Using a timespan would solve the problems as it has many attributes:
DateTime strt_date = DateTime.Now;
DateTime end_date = Convert.ToDateTime("10/1/2017 23:59:59");
//DateTime add_days = end_date.AddDays(1);
TimeSpan nod = (end_date - strt_date);
Console.WriteLine(strt_date + "" + end_date + "" + "" + nod.TotalHours + "");
Console.ReadKey();
For a and b as two DateTime types:
DateTime d = DateTime.Now;
DateTime c = DateTime.Now;
c = d.AddDays(145);
string cc;
Console.WriteLine(d);
Console.WriteLine(c);
var t = (c - d).Days;
Console.WriteLine(t);
cc = Console.ReadLine();
For beginners like me that will stumble upon this tiny problem, in a simple line, with sample conversion to int:
int totalDays = Convert.ToInt32((DateTime.UtcNow.Date - myDateTime.Date).TotalDays);
This calculates the total days from today (DateTime.UtcNow.Date) to a desired date (myDateTime.Date).
If myDateTime is yesterday, or older date than today, this will give a positive (+) integer result.
On the other side, if the myDateTime is tomorrow or on the future date, this will give a negative (-) integer result due to rules of addition.
Happy coding! ^_^
First declare a class that will return later:
public void date()
{
Datetime startdate;
Datetime enddate;
Timespan remaindate;
startdate = DateTime.Parse(txtstartdate.Text).Date;
enddate = DateTime.Parse(txtenddate.Text).Date;
remaindate = enddate - startdate;
if (remaindate != null)
{
lblmsg.Text = "you have left with " + remaindate.TotalDays + "days.";
}
else
{
lblmsg.Text = "correct your code again.";
}
}
protected void btncal_Click(object sender, EventArgs e)
{
date();
}
Use a button control to call the above class. Here is an example:
You can use the code below:
int DateDifInSecond = EndDate.Subtract(StartDate).TotalSeconds
Get the difference between the two dates and then get the days from:
int total_days = (EndDate - StartDate).TotalDays
try this truly worked Get actual days diff. date format is "dd/MM/yyyy"
string[] d1 = txtFromDate.Values.Split('/');
string[] d2 = txtToDate.Values.Split('/');
DateTime FrmDt = new DateTime(Convert.ToInt32(d1[2]), Convert.ToInt32(d1[1]), Convert.ToInt32(d1[0]));
DateTime ToDt = new DateTime(Convert.ToInt32(d2[2]), Convert.ToInt32(d2[1]), Convert.ToInt32(d2[0]));
TimeSpan TDiff = ToDt.Subtract(FrmDt);
String DaysDiff = TDiff.TotalDays.ToString();
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
DateTime d = Calendar1.SelectedDate;
// int a;
TextBox2.Text = d.ToShortDateString();
string s = Convert.ToDateTime(TextBox2.Text).ToShortDateString();
string s1 = Convert.ToDateTime(Label7.Text).ToShortDateString();
DateTime dt = Convert.ToDateTime(s).Date;
DateTime dt1 = Convert.ToDateTime(s1).Date;
if (dt <= dt1)
{
Response.Write("<script>alert(' Not a valid Date to extend warranty')</script>");
}
else
{
string diff = dt.Subtract(dt1).ToString();
Response.Write(diff);
Label18.Text = diff;
Session["diff"] = Label18.Text;
}
}

Categories