Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Hello I am quite new to C# and I am facing difficulty in adding time as an int . For example,
01:30 Hr
09:45 Hr
13:27 Hr
are hours. I want to convert these to minutes.
How do I add these as int so that I get:
90 + 585 + 825
Is there a way to perform this operation in C#?
public int total_time;
void Start()
{
total_time = time_1 + time_2 + time_3;
}
Let's suppose that your time data are stored in this way:
var dataSource = new List<string>
{
"01:30 Hr",
"09:45 Hr",
"13:27 Hr"
};
Then all you need to do is to
get ride of the Hr suffix
convert them to TimeSpan
sum their TotalMinutes
var total = dataSource
.Select(data => data.Substring(0, 5))
.Select(time => TimeSpan.Parse(time).TotalMinutes)
.Sum();
Obviously this is a naive implementation and really fragile.
A more robust solution would use
regex to get the time portion of the string
use TimeSpan's TryParse to avoid runtime exceptions in case of mailformed inputs.
UPDATE
Based on the comment of Drag and Drop, here is an alternative which could give you better precision:
var total = dataSource
.Select(data => data.Substring(0, 5))
.Select(time => TimeSpan.Parse(time))
.Aggregate(TimeSpan.Zero, (t1, t2) => t1 + t2)
.TotalMinutes;
This approach could be used as well whenever you introduce seconds as well.
(You just need to adjust the Substring parameters.)
Why don't you use TimeSpan struct? TimeSpan struct does exactly what you want.
TimeSpan thirtyMinute = new TimeSpan(0, 30, 0); // Hours, Minutes, Seconds
TimeSpan s = new TimeSpan(1, 24, 60, 60, 100); // Day, Hours, Minutes, Seconds, Miliseconds
TimeSpan oneHour = thirtyMinute + thirtyMinute; // You can add TimeSpan to another == 1 Hour
Here is how to convert hour string
Debug.Log(string.Format("You were out of game for: {0} minutes and {1:00} seconds", (int)totalExitTime / 60, (int)totalExitTime % 60));
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 months ago.
Improve this question
I have a period suppose its Start from 01/12/2022 and end in 30/12/2022 I want to divide this period to weeks the week must start from Saturday and end in Friday so expected result should be :
How I can do this using SQL server query
After a little bit of trial and error you need this:
DateTime StartOfWeek(DateTime when) =>
when.AddDays(-((8 + (int)when.DayOfWeek) % 7));
Here's a table of output:
var table =
Enumerable
.Range(0, 31)
.Select(x => new DateTime(2022, 12, 1).AddDays(x))
.GroupBy(x => StartOfWeek(x))
.Select(x => new
{
from = x.Min(),
to = x.Max(),
start = x.Key
});
A similar solution to Enigmativity's, for those who are not yet familiar with queries.
In general, you can find out the first day of the week like this:
(and choose which day the week should start)
DateTime curDate = new DateTime(2022, 12, 1);
DateTime result = FirstDateOfWeek(curDate, DayOfWeek.Saturday);
DateTime FirstDateOfWeek(DateTime day, DayOfWeek firstDayOfWeek=DayOfWeek.Monday)
{
int minus = day.DayOfWeek - firstDayOfWeek;
if (minus == 0)
return day.Date;
if (minus < 0)
minus = 7 + minus;
return day.Date - TimeSpan.FromDays(minus);
}
Just add 7 to the result for the next week.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am fairly new to programming.
I am trying to create a bool array based on 30 minute intervals within a day, therefore the size of the array will be 48 (24 hours * 2(30 min intervals)). All the values will be false to begin with, but based on Start Time and End Time, I want to set values to true.
For example,
StartTime : 02:00:00
EndTime: 04:00:00
I want the boolean array to look like:
F, F, F, F, T, T, T, T, F, F ...
Here is an example of how to create the array you described.
public bool[] timeCheck(DateTime start, DateTime end)
{
bool[] output = new bool[48];
int startIndex = ((start.Hour * 60) + start.Minute)/30;
int endIndex = ((end.Hour * 60) + end.Minute)/30;
for (int i = startIndex ;i <= endIndex; i++)
output[i] = true;
return output;
}
In this code we define the start and end indices allowing us to only spend time on the values we need to set to true, all other values are left as the default value of false
The reason we can do this confidently is because we are using the DateTime and int type so we know that the startIndex and endIndex must exist within our array. the maximum value for (start.Hour * 60) + start.Minute) is 1,439 min. When this is divided by 30 we get 47 the last index of our array.
If start time comes after end time, we simply have no true values as the for loop ends immediately.
This code does not take into account difference in the date, it only accounts for time. So if your start is 10pm on Wednesday and your end 2am on Thursday no values are true. I will leave that one up to you to solve.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Is there a simpler way to calculate this? Perhaps via a method built-in to .NET?
var time = DateTime.Now.AddSeconds(8);
var year = 10000000000000 * (ulong)(time.Year - 1900);
var month = 100000000000 * (ulong)(time.Month - 1);
var dayofyear = 100000000 * (ulong)(time.DayOfYear - 1);
var day = (ulong)(time.Day * 1000000);
var Hour = (ulong)(time.Hour * 10000);
var Minute = (ulong)(time.Minute * 100);
var Second = (ulong)(time.Second);
var utcTime = year + month + dayofyear + day + Hour + Minute + Second;
Could it be DateTime.Now.AddSeconds(8).AllMilliseconds?
I've tried these methods
var test = (time - DateTime.MinValue).Milliseconds;
var tes2t = (time - DateTime.MinValue).TotalMilliseconds;
DateTime.MinValue is not 1900. The documentation for DateTime.MinValue says:
The value of this constant is equivalent to 00:00:00.0000000 UTC, January 1, 0001, in the Gregorian calendar.
Which is about 1899 years before the date you want. You want to do this:
double milliseconds = ( time - new DateTime( 1900, 1, 1 ) ).TotalMilliseconds
EDIT: As Rick suggests in the comments, the following might be better suited to your needs:
var epoch = new DateTime( 1900, 1, 1, 0, 0, 0, DateTimeKind.Utc );
double milliseconds = ( time - epoch ).TotalMilliseconds;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Im looking for a way to combine my integers together.
I got 3 integers i want to make one from them.
All the integers are holding a time currency wich looks a little like this:
var date = DateTime.Now;
int timeHours = date.Hour;
I got the Hours, Minutes and Seconds and want to combine so they would look like this:
Hour : Minutes : Seconds
How can i combine the integers together to do that.
Note: I've looked on the internet but i could not get the information i was looking for.
This is what i looked at:
Combine two integers to create a unique number
How to combine 2 integers in order to get 1?
Combining these integers will generate a string, not an another integer. You can easily format your DateTime with ToString() method like;
var str = DateTime.Now.ToString("H':'m':'s"); // eg: 11:0:2
If you wanna get your hour, minute and second part with leading zeros for single digits, you can use HH:mm:ss format instead.
var str = DateTime.Now.ToString("HH':'mm':'ss"); // eg: 11:00:02
DateTime.Now already contains all information you need, date and time. All you need to do is format this information
There're many ways to pack two (or many) integers into one based
on their ranges, e.g.
int i1 = 123;
int i2 = 456;
// two 32-bit integers into 64-bit one
long result = (((long) i1) << 32) | i2;
In your particular case
int hours = 5;
int minutes = 10;
int seconds = 59;
int combined = hours * 3600 + minutes * 60 + seconds;
reverse:
int combined = 12345;
int seconds = combined % 60;
int minutes = (combined / 60) % 60;
int hours = combined / 3600;
you can try the below code i think it's useful
var date = DateTime.Now;
var result = date.Hour + ":" + date.Minute + ":" + date.Second;
Console.WriteLine(result);
A simple way using the base 10 number system is to just
var number = hours * 10000 + minutes * 100 + seconds
this returns a number like 150936 for 15:09:36
To convert back:
seconds = number % 100
minutes = (number / 100) % 100
hours = number / 10000
Note that this is obviously not the most efficient approach, but simple
You should cast to string with format function for example:
string result = string.Format("{0:00}:{1:00}:{2:00}", timeHours, timeMinutes, timeSeconds);
Just to be complete:
format HH:mm:ss:
string result = string.Format("{0:00}:{1:00}:{2:00}", timeHours, timeMinutes, timeSeconds);
string result = DateTime.Now.ToString("HH:mm:ss");
format H:m:s:
string result = string.Format("{0}:{1}:{2}", timeHours, timeMinutes, timeSeconds);
string result = DateTime.Now.ToString("H:m:s");
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I created a count down timer like this:
I set manuel values for startTime
var options = {
stepTime: 60,
format: "dd:hh:mm:ss",
startTime: "01:12:32:55",
digitImages: 6,
digitWidth: 53,
digitHeight: 77,
image: "digits.png"
};
I have lblDay,lblHours,lblMinutes,LblSeconds on page.
I can get TotalHours column from SQL.How can I convert value of TotalHours to like this :
lbDays:27
lblHours:2
lblMinutes:34
lblSeconds:08
int TotalHours = Convert.ToInt32(dt.Rows[0][11]);
//int TotalHours =664
and How can I set value of labels to startTime
int totalHours = 664; // example from question
TimeSpan ts = TimeSpan.FromHours(totalHours); // or similar
int days = (int)ts.TotalDays,
hours = ts.Hours,
// note the next will always be zero
// since we init in an integer
// number of hours
minutes = ts.Minutes,
seconds = ts.Seconds;