I am trying to make a digital clock in C#. I have 3 counter objects for hours, minutes and seconds. It has to be in format hh:mm:ss.
What I managed to do
String hours = _hours.Value.ToString();
String minutes = _minutes.Value.ToString();
String seconds = _seconds.Value.ToString();
if (hours.Length == 1)
{
hours = "0" + hours;
}
if (minutes.Length == 1)
{
minutes = "0" + minutes;
}
if (seconds.Length == 1)
{
seconds = "0" + seconds;
}
return hours + ":" + minutes + ":" + seconds;
It works but I am trying for a more efficient way of doing it using String.format. I have tried few different regular expressions but have been unsuccessful.
string b = string.Format("{0:D2}:{1:00}:{2:d2}", hours, minutes, seconds);
Cheers
Have you tried converting the string into int, before trying your string.Format? Something like below
string.Format("{0:00}:{1:00}:{2:00}",
int.Parse(hours), int.Parse(minutes), int.Parse(seconds));
If _hours.Value, _minutes.Value and _seconds.Value are numeric types, then you can use the below code which is more efficient
string.Format("{0:00}:{1:00}:{2:00}",
_hours.Value, _minutes.Value, _seconds.Value);
You can always try something a bit different:
DateTime dt = new DateTime(2000, 1, 1, hours, minutes, seconds); // just ignore year, month and day
var x = dt.ToString("HH:mm:ss");
IMO if you already have a string type it's useless to cast it to int or DateTime just to stringify it again after that.
I would use String.PadLeft method :
string h = hours.PadLeft(2, '0');
string m = minutes.PadLeft(2, '0');
string s = seconds.PadLeft(2, '0');
string result = h + ":" + m + ":" + s;
PadLeft will make your string to always have length at least of the value passed as a first parameter ( 2 in this case ) and fill "empty" places with the value passed in second parameter ( 0 in this case ).
Check this online
You can use the formatting options available on the ToString() method of DateTime like below:
(new DateTime(1900, 1, 1, _hours.Value, _minutes.Value, _seconds.Value)).ToString("HH:mm:ss");
You can try using:
string b = DateTime.Now.ToString("HH:mm:ss");
If you have some date variable, you can do so:
string b = dateVar.ToString("HH:mm:ss");
If you want solution exactly for your example, then:
return string.Format("{0:00}:{1:00}:{2:00}",
int.Parse(hours),
int.Parse(minutes),
int.Parse(seconds)
);
Related
This question already has answers here:
Convert TimeSpan from format "hh:mm:ss" to "hh:mm"
(7 answers)
Closed 4 years ago.
Beginner in xamarin. Im tring to display the time as HH:mm without the seconds being added in. It appears on my form as example 12:30:00, i want just as 12:30. Do i need to change Date time function maybe, the code is currently working but displaying the time as hour minute seconds still.
The code also should allow the soonest time to appear at the top but it doesnt seem to be doing that either.
void FindNextDue(ObservableCollection<UserMedDosagePayLoad> medtimes)
{
UserMedTimesFilteredList.Clear();
int nowHour = DateTime.Now.Hour;
int nowMinutes = DateTime.Now.Minute;
TimeSpan now = new TimeSpan(nowHour, nowMinutes, 0);
foreach (UserMedDosagePayLoad item in medtimes)
{
item.Nextduemessage = item.Dosage + " " + item.Dosageunit +
"due at " + item.Time;
string[] DT = item.Time.Split(':');
if (DT[0] != null)
{
int hr = Convert.ToInt32(DT[0]);
int minutes = Convert.ToInt32(DT[1]);
TimeSpan medTime = new TimeSpan(hr, minutes, 0);
TimeSpan comparison = now.Subtract(medTime).Negate();
TimeSpan TwentyFourHour = new TimeSpan(24, 0, 0);
if (comparison.TotalMilliseconds <0)
{
comparison = TwentyFourHour.Add(comparison);
}
TimeComparison.Add(comparison);
}
}
//Order the collection of times so the next due is always first
TimeComparison = new List<TimeSpan>(TimeComparison.OrderBy(h => h.Hours)
.ThenBy(m => m.Minutes));
List<string> UserMedIDs = new List<string>();
for (int i = 0; i < TimeComparison.Count(); i++)
{
DateTime NextDue = DateTime.Now.Add(TimeComparison[i]);
DateTime NextDueToCompare = new DateTime(NextDue.Year, NextDue.Month,
NextDue.Day, NextDue.Hour, NextDue.Minute, 0);
string NextDueComparisonString = NextDueToCompare.ToString("HH:mm:ss");
foreach (UserMedDosagePayLoad item in UserMedTimes)
{
if (item.Time == NextDueComparisonString &&
!UserMedIDs.Contains(item.Usermedid))
{
UserMedTimesFilteredList.Add(item);
UserMedIDs.Add(item.Usermedid);
}
}
UserMedTimes = medtimes;
MedicationList.ItemsSource = UserMedTimesFilteredList;
BusyIndicator.IsRunning = false;
}
}
If you only want hours and minutes to display, then remove "ss" from your format string
string NextDueComparisonString = NextDueToCompare.ToString("HH:mm:ss");
here, you are not specifying any format so it is using the default
item.Nextduemessage = item.Dosage + " " + item.Dosageunit +
"due at " + item.Time;
specify a format like this
item.Nextduemessage = item.Dosage + " " + item.Dosageunit +
"due at " + item.Time.ToString("HH:mm");
Use formatting if you don't want to see the seconds at all (12:48 for example).
The method gets a TimeSpan obj, and returns the time as a string without the seconds.
Read here to explore more about formatting.
The custom function
public string GetTimeSpanWithoutSeconds(TimeSpan input)
{
return input.ToString(#"hh\:mm");
}
The "hh" custom format specifier
Represents the hour as a number from 01 through 12; that is, the hour is represented by a 12-hour clock that counts the whole hours since midnight or noon. A particular hour after midnight is indistinguishable from the same hour after noon. The hour is not rounded, and a single-digit hour is formatted with a leading zero. For example, given a time of 5:43 in the morning or afternoon, this format specifier displays "05".
The "mm" custom format specifier
Represents the minute as a number from 00 through 59. The minute represents whole minutes that have passed since the last hour. A single-digit minute is formatted with a leading zero.
I'm trying to subtract between two dateTimes in a way that I'll see all totaled hours.(including mm and ss if theres any)
for Example:
TimeSpan j = DateTime.Parse("06/05/2015 12:00:00").Subtract(DateTime.Parse("04/05/2015 14:00:00"));
I want to return a string that contains "46:00:00"
TimeSpan j = DateTime.Parse("06/05/2015 12:00:00").Subtract(DateTime.Parse("05/05/2015 12:00:00"));
I want to return a string that contains "24:00:00"
TimeSpan j = DateTime.Parse("06/05/2015 12:00:00").Subtract(DateTime.Parse("05/05/2015 18:00:00"));
I want to return a string that contains "18:00:00"
You can use TimeSpan.TotalHours and String.Format:
string result = string.Format("{0:D2}:{1:D2}:{2:D2}", (int)j.TotalHours, j.Minutes, j.Seconds);
The cast to int is needed to remove the fractional part from the TotalHours.
The D2 ensures that you always get two digits like 00 even if the minute part is 0.
MSDN: The "D" (or decimal) format specifier
Try Something like this,
I have done only for your first condition
DateTime d1 = Convert.ToDateTime( "06/05/2015 12:00:00");
DateTime d2 = Convert.ToDateTime( "04/05/2015 14:00:00");
TimeSpan j = d1 - d2;
string ti = (j.TotalHours + " : " + j.TotalMinutes + " : " + j.TotalSeconds).ToString();
i have done something like:
TimeSpan j = DateTime.Parse("06/05/2015 12:00:00").Subtract(DateTime.Parse("04/05/2015 14:00:00"));
int i = 0;
if(j.Days >= 1)
{
i = j.Days * 24;
i = i + j.Hours;
}
string s = String.Concat(i.ToString(), ":", j.Minutes.ToString(), ":", j.Seconds.ToString());
ok basically I have a program that is re-writing text files and formatting them through various conditions, one of the conditions is that the date and time values in my original text file needs to be removed from its current location and moved into a new column I have created, this is done with the code below. I used a regex to find the date and time format and then remove it from its current location and store the value in a variable that I can use later...
if (line.Contains(date))
{
string pattern = #"(\d{2}:\d{2}:\d{2}\s?\d{2}/\d{2}/\d{4})";
string input = line;
string replacement = "";
Regex rgx = new Regex(pattern);
date1 = rgx.Match(input).ToString();
string result = rgx.Replace(input, replacement);
line = result;
}
This new value that is returned gets both the time and date values but only as one string, so I then used a split (shown below) to get the two values separate, now split[0] is my time variable (00/00/00 format) - which I now need to round up to the nearest hour. I am really not sure how to go about this, any ideas ?
string[] split = date1.Split(' ');
writer.WriteLine(split[0] + "\t" + split[1] + "\t" + line);
Get that date from the string into a DateTime struct. See for example the TryParseExact method
Then you can create a new DateTime value, based on year/month/day/hour of the value from the previous step, setting the minute and second parts to zero (see here )
Add one hour if the minutes or seconds part (of your first value) is not zero, using .AddHours(1), which returns a new DateTime value.
EDIT
Some sample code:
string inputdate = "2:56:30 8/7/2014";
DateTime dt;
System.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-US");
if (DateTime.TryParseExact(inputdate, "H:m:s d/M/yyyy", // hours:minutes:seconds day/month/year
enUS, System.Globalization.DateTimeStyles.None, out dt))
{
// 'dt' contains the parsed date: "8-7-2014 02:56:30"
DateTime rounded = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, 0, 0);
if (dt.Minute > 0 || dt.Second > 0) // or just check dt.Minute >= 30 for regular rounding
rounded = rounded.AddHours(1);
// 'rounded' now contains the date rounded up: "8-7-2014 03:00:00"
}
else
{
// not a correct date
}
In my case, I need to round it to lower hour, and I used this logic:
DateTime x = new DateTime();
x = x.Date.AddHours(x.Hour);
You can try one liner solution to convert your DateTime to nearest hour,
//Input DateTime
DateTime input = DateTime.ParseExact("28/05/2021 2:16 PM", "dd/MM/yyyy h:mm tt", CultureInfo.InvariantCulture);
//Ternary Operation
var output = input.Minute > 30 //Check if mins are greater than 30
? input.AddHours(1).AddMinutes(-input.Minute) //if yes, then add one hour and set mins to zero
: input.AddMinutes(-input.Minute); //otherwise set mins to zero
Console.WriteLine(result.ToString());
Try Online: .NET Fiddle
Can you convert the string to a datetime?
Something like:
dateVariable = Convert.ToDateTime(dateString);
int hour = dateVariable.Hour;
int minute = dateVariable.Minute;
And then do the rounding.
Now as you have
string[] str = split[1].Split('/');
// create a new DateTime
int minutes = int.Parse(str[1]);
if(minutes >= 30)
hour = int.Parse(str[0]) + 1 // make sure if it 13 or 25 make it 1
minutes = 0 ;
sec = 0;
else {
hour = int.Parse(str[0]);
minutes = 0 ;
sec = 0 ;
}
var myDate = new Date(Year, month , day , hour , minutes , sec);
In C#
var Now = DateTime.Now;
var Nearest = Now.Date;
Nearest = Nearest.AddHours(Now.Hour + (Now.Minute >= 30 ? 1 : 0));
Now = Current time
Nearest = Rounded to the nearest hour
I have a data table, from Sage 100 ERP to be specific, that uses two separate columns to store the updated date and time (DateUpdated and TimeUpdated). I need to convert the data in these two fields to a DateTime object for comparisons. The dates look like "mm/dd/yyyy 12:00 AM" and the time is a decimal like 14.29297. So far I have been able to convert the time to the minute as follows:
private DateTime GetDateTime(string date, decimal time)
{
int hour = int.Parse(Math.Floor(time).ToString());
decimal minTemp = decimal.Parse((60 * (time - hour)).ToString());
int min = int.Parse(Math.Round(minTemp).ToString());
int sec = int.Parse(Math.Round(60 * (minTemp - min)).ToString());
string datetime = date + " " + hour.ToString() + ":" + min.ToString();
return DateTime.Parse(datetime);
}
I remove the 12:00AM from the date string before I pass it to this method. This works, but I'm loosing the seconds which is very important.
How can I convert the time to hours, minutes, and seconds?
It looks like you could avoid all that extra processing and just do this:
DateTime GetDateTime(string date, decimal time)
{
return DateTime.Parse(datetime).AddHours((double)time);
}
Just parse what you have:
private DateTime GetDateTime(string date, decimal time)
{
DateTime dt = DateTime.ParseExact(date, "MM/dd/yyyy hh:mm tt",
CultureInfo.InvariantCulutre);
double hours = Convert.ToDouble(time);
return dt.AddHours(hours);
}
Of course, it would be a lot easier if you had the correct data types to begin with. I have a feeling somewhere you have a DateTime and a double anyway (perhaps when you read the data from the database), and you are improperly converting them to string and decimal.
if it's not a typo - you are missing to append seconds value to the datetime string.
Replace This:
string datetime = date + " " + hour.ToString() + ":" + min.ToString();
With this:
string datetime = date + " " + hour.ToString() + ":" + min.ToString()+ ":" + sec.ToString();
Assuming your calculations are correct, did you try appending the second component to the datetime variable as follows:
string datetime = date + " " + hour.ToString() + ":" + min.ToString()
+ ":" + sec.ToString()
For the seconds try something like this:
int secTemp = int.Parse((Math.Round(60 * (minTemp - min))).ToString());
int sec = (secTemp<0?60 + secTemp:secTemp);
string datetime = date + " " + hour.ToString() + ":" + min.ToString()+ ":" + sec.ToString();
Hope it helps
Covert Decimal to Hour and Minute for single Database field
double convertData = 1.75
TimeSpan timespan = TimeSpan.FromHours(convertData);
string outputH = timespan.ToString("hh");
string outputM = timespan.ToString("mm");
Output will be 1 hour / 45 min
Hello i got array of string, and they are durations made by myself in format H:M:S:MS
Example strings:
0:0:4:410
0:0:1:425
0:0:1:802
0:0:1:509
0:0:1:674
0:0:1:628
0:0:2:76
How can i sum/avg/min/max values of these items in arraylist?
Arraylist name is arrayLL.
I'm new in c# so hope someone will show me how to work with strings.
The function that adds to array is:
if (Session["DT"].ToString() != "")
{
TimeSpan ts = ((DateTime)Session["DT2"]).Subtract((DateTime)Session["DT"]);
Session["TimeL"] = ts.Hours.ToString() + ":"
+ ts.Minutes.ToString() + ":"
+ ts.Seconds.ToString() + ":"
+ ts.Milliseconds.ToString();
}
Assuming the numbers represent hours, minutes, seconds, and milliseconds you can try the following:
// Empty list you will populate:
List<int> durationsInMilliseconds = new List<int>();
// Loop through your existing data, and calculate all
// durations into milliseconds:
foreach (string word in yourDurationArray)
{
string[] values = s.Split(':');
int hoursAsMilliseconds = Integer.parse(values[0]) * 60 * 60 * 1000;
int minutesAsMilliseconds = Integer.parse(values[1]) * 60 * 1000;
int secondsAsMilliseconds = Integer.parse(values[2]) * 1000;
int sumDurationAsMilliseconds = hoursAsMilliseconds +
minutesAsMilliseconds +
secondsAsMilliseconds +
Integer.parse(values[3]);
durationsInMilliseconds.add(sumDurationAsMilliseconds);
}
Now you should have a list of type Integer (durationsInMilliseconds) which contains the numbers in a single comparable format. With this, you should be able to do whichever calculations you need.
(PS: If you need the result in the same format as the original input-data, you will have to add an operation for calculating back from MS into hours, minutes and seconds..)
Since i guess they are Durations so i you should do this
var enu_ts = yourvariable.OfType<string>().Select(x =>
TimeSpan.Parse(x, #"h\:m\:s\:fff", CultureInfo.InvariantCulture));
Max
var max = enu_ts.Max().ToString();
Min
var max = enu_ts.Min().ToString();
foreach(string s in dateString)
{
spanList[i] = TimeSpan.Parse(s);
total=total.Add(spanList[i++]);
}
Response.Write("Max TimeSpan:"+spanList.Max<TimeSpan>());
Response.Write("Min TimeSpan:" + spanList.Min<TimeSpan>());
Response.Write("Total Sum of TimeSpan:"+total);