This question already has answers here:
What is the easiest way to subtract time in C#?
(7 answers)
Closed 6 years ago.
in C# unity i want to do time minus time.
I have an example below :
Time1:
int Hour = 12;
int Minutes = 0;
Int Seconds = 0;
Time2:
int LastHour = 1;
int LastMinutes = 3;
int LastSeconds = 20;
Actually i want that the result is like below :
Result:
int ResultHour = 10;
int ResultMinutes = 56;
int ResultSeconds = 40;
If Time1 - Time2 it Will get Like Result
How to do it in C# unity ?
You can use the TimeSpan structure:
var time1 = new TimeSpan(12, 0, 0);
var time2 = new TimeSpan(10, 56, 40);
var result = time1 - time2; // will be 01:03:20
To get the specific time parts, access the Hours, Minutes and Seconds properties of result.
TimeSpan is you way:
TimeSpan result = (new TimeSpan(Hour, Minutes, Seconds)
- new TimeSpan(LastHour, LastMinutes, LastSeconds));
int ResultHour = result.Hours;
int ResultMinutes = result.Minutes;
int ResultSeconds = result.Seconds;
Related
I need to make a program that reads 4 integer inputs.
int examHour
int examMin
int hourArrival
int minuteArrival
Then I have 3 options
Early, if 30 or more minutes earlier.
On time, if the student is on time or 30 min earlier
Late.
I know there is a > < method to do it, but I am 100% sure there is a smarter DateTime or TimeSpan method to do it.
If student is early I have to write
Early {minutes} earlier for less than hour earlier.
HH:mm hours before start for early for a hour or more.
late {minutes} late for less than hour late.
HH:mm hours late for late for a hour or more.
namespace OnTime
{
class Program
{
static void Main(string[] args)
{
int examHour = int.Parse(Console.ReadLine());
int examMin = int.Parse(Console.ReadLine());
int hourArrival = int.Parse(Console.ReadLine());
int minuteArrival = int.Parse(Console.ReadLine());
string total = ($"{examHour}:{examMin}");
string totald = ($"{hourArrival}:{minuteArrival}");
DateTime arrival = new DateTime();
arrival = DateTime.ParseExact(total, "H:m", null);
string resultone = (arrival.ToString("H:mm"));
DateTime exam = new DateTime();
exam = DateTime.ParseExact(totald, "H:m", null);
string resulttwo = (exam.ToString("H:mm"));
DateTime starttime = Convert.ToDateTime(arrival);
DateTime arrivaltime = Convert.ToDateTime(exam);
Console.WriteLine ($"Early {HH:mm} before start")
Console.WriteLine ($"Late {HH:mm} after start")
}
}
}
It seems to me that you can do your computations and avoid DateTime or TimeSpan altogether.
double exam = examHour + examMin / 60.0;
double arrival = hourArrival + minuteArrival / 60.0;
double delta = exam - arrival;
string status = delta > 0.5 ? "Early" : (delta < 0.0 ? "Late" : "On time");
This just creates a double with the value being hours with a decimal fraction representing the minutes.
using System;
namespace OnTime
{
class Program
{
static void Main(string[] args)
{
int examHour = int.Parse(Console.ReadLine());
int examMin = int.Parse(Console.ReadLine());
int hourArrival = int.Parse(Console.ReadLine());
int minuteArrival = int.Parse(Console.ReadLine());
string total = ($"{examHour}:{examMin}");
string totald = ($"{hourArrival}:{minuteArrival}");
DateTime arrival = new DateTime();
arrival = DateTime.ParseExact(total, "H:m", null);
DateTime exam = new DateTime();
exam = DateTime.ParseExact(totald, "H:m", null);
TimeSpan span = arrival - exam;
int hours = span.Hours;
int minutes = span.Minutes;
string timediff = hours.ToString("0") + ":" + minutes.ToString("00");
string minutesdiffOne = minutes.ToString("00");
if (examHour < hourArrival && (examMin - minuteArrival < 30))
Console.WriteLine("on time");
Console.WriteLine($"{minutesdiff:F0}");
}
}
}
I have a int months (84 for example) and I need to work out how many years that equals so using 84 = 7 years
I need to loop through the initial number and see how many full years are in there and print the result
example:
int count = 84;
for (int i = 12; i <= count; i++)
{
years = i;
}
This doesn't work of course, it produces '84 years' where I should produce 7 years. I also need to get the remaining months after the year calculation so if the initial number was 85 for example it would result in 7 years 1 month.
Use standard mathematical operations instead of a loop:
int count = 84;
int years = count / 12;
int months = count % 12;
First one is division, second is modulus.
Because both count and 12 are integers count/12 returns an integer as well. So for 85 it will return 7, not 7.1.
Update
Loop version could look like that:
count = 84;
years = 0;
for (int i = 12; i <= count; i += 12)
{
years++;
}
Doing that with a loop would look like this:
int years = 0;
while (count >= 12) {
count -= 12;
years++;
}
However, you can do the same without looping:
int years = count / 12;
count %= 12;
Try this:
DateTime t = new DateTime();
t = t.AddMonths(84);
int year = t.Year; // year = 8
int month = t.Month; // month = 1
Surely you just need basic math operations:
int count = 84;
int years = (int)(count / 12);
int months = count % 12;
int years = count / 12;
int remainingMonths = count % 12;
thanks to everyone who gave a answer :D much appreciated
i got it working like this in the end
int employmentInMonthsAmount = this.MaxEmploymentHistoryInMonths;
var intcounter = 0;
int years = 0;
for (var i = 0; i < employmentInMonthsAmount; i++)
{
if (intcounter >= 12)
{
years++;
intcounter = 0;
}
intcounter++;
}
var monthsleft = intcounter;
I have an 6digit integer, let's say "153060" that I'll like to split into
int a = 15 (first 2 digits),
int b = 30 (second 2 digits),
int c = 60 (third 2 digits),
The first thing that comes to mind is to convert the int to a string, split it using SubString (or a variation), and then convert back to an int.
This seems like a highly inefficient way to do it though. Can anyone recommend a better/faster way to tackle this?
Thanks!
Additional Info: the reason for splitting the int is because the 6-digit integer represents HHMMSS, and I'd like to use it to create a new DateTime instance:
DateTime myDateTime = new DateTime (Year, Month, Day, a , b, c);
However, the user-field can only accept integers.
int y = number / 10000;
int m = (number - y*10000) / 100;
in d = number % 100;
If your end goal is a DateTime, you could use TimeSpan.ParseExact to extract a TimeSpan from the string, then add it to a DateTime:
TimeSpan time = TimeSpan.ParseExact(time, "hhmmss", CultureInfo.InvariantCulture);
DateTime myDateTime = new DateTime(2011, 11, 2);
myDateTime = myDateTime.Add(time);
(Assumes >= .NET 4)
How about something like this?
int i = 153060;
int a = i / 10000;
int b = (i - (a * 10000)) / 100;
int c = (i - ((a * 10000) + (b * 100)));
You can do that without converting to string with:
int a = 153060 / 10000;
int b = (153060 / 100) % 100;
int c = 153060 % 100;
I am not sure about how efficient that is compared to converting to string. I think this is only 4 operations. So it might be faster.
I am trying make a clock. The hour is a string. I want to put that hour into a char array so i can separate the hour into one or two indexes. That way i can use a case on the individual indexes to ultimately bind it to a grid and draw a line for the digital time..
So, the hour is converted to an array. But i want to take the first index 0 and store it into a string or int so i can pass it into a function where i can use a case on it. if i leave it as a char and convert it to an int i get a number like 50 which is no good.
So, when i try to assign the first index of the array to a string it wont let me convert from array to string.
hr1 = hours[0];
What is my best option of seperating the hour into separate indexes and then converting it over to the proper int? Also, the time is on 24 hour and i would like it to be 12 hour.
private void _timer_Elapsed(object sender, EventArgs e)
{
DateTime now = DateTime.Now;
//DigitalTime = now.ToString("hh:mm:ss tt");
//DigitalTime = now.ToString();
//DigitalTime = DateTime.Now.Hour.ToString();
SecondAngle = now.Second * 6;
MinuteAngle = now.Minute * 6;
HourAngle = (now.Hour * 30) + (now.Minute * 0.5);
string hrs, hr1, hr2;
char[] hours = new char[15];
hrs = DateTime.Now.Hour.ToString("hh:mm:ss tt");
hours = hrs.ToCharArray();
if (hours.Length > 1)
{
hr1 = hours[0]; // error -
hr2 = hours[1];
// SetHourDigit1(Convert.ToInt32(hr1));
}
else
{
// hr1 = '0';
hr2 = hours[0];
}
}
public void SetHourDigit1(int num)
{
switch (num)
{
case 0:
MessageBox.Show("num" + num);
break;
case 1:
MessageBox.Show("num" + num);
break;
case 2:
break;
}
}
I would avoid messing with strings and char arrays altogether. Use arithmetic instead:
int hour = DateTime.Now.Hour;
int leastSignificantDigit = hour % 10;
int mostSignificantDigit = hour / 10;
// Use one of these as input for your switch statement.
% is the modulo operator; the remainder of a division by 10 in this case.
Edit: I noticed you want to have a 12-hour clock. You can add some additional computation for this. Replacement for the first line of code:
int hour = DateTime.Now.Hour % 12;
if (hour == 0) hour = 12;
if (hours.Length > 1)
{
hr1 = hours[0].ToString(); // no error -
hr2 = hours[1].ToString();
// SetHourDigit1(Convert.ToInt32(hr1));
}
but if you want to get parts of time use this:
dateparts = datestring.splite(':');
string hour = dateparts[0];
string minute = dateparts[1];
string s = dateparts[2];
now you have hour,minute,second and t.
because of you can trust the parts use int.parse to convert them to int.
int nhour = int.parse(hour);
int nminute = int.parse(minute);
int nsecond = int.parse(s);
for 24 hours
hrs = DateTime.Now.Hour.ToString("HH:mm:ss");
This is a usefull link for u:
DateTime.ToString() Pattern
Use the modulo (%) operator to convert the 24 hour value to 12 hours, and also to get the second digit of the two digit number. There is no reason to format it as a string and then convert it back to numbers.
private void _timer_Elapsed(object sender, EventArgs e) {
DateTime now = DateTime.Now;
int hour12 = now.Hour % 12;
SecondAngle = now.Second * 6;
MinuteAngle = now.Minute * 6;
HourAngle = (hour12 * 30) + (now.Minute * 0.5);
SetHourDigit1(hour12 / 10);
SetHourDigit2(hour12 % 10);
}
I want to get a six digit number by user and spit it into 3 parts as(day, month, year)
Example:
int date=111213;
day =11;
month =12;
year =13;
I think I have to convert it into string then by using substring() I can do this.
Any easy Idea ??
How about:
// Assuming a more sensible format, where the logically most significant part
// is the most significant part of the number too. That would allow sorting by
// integer value to be equivalent to sorting chronologically.
int day = date % 100;
int month = (date / 100) % 100;
int year = date / 10000;
// Assuming the format from the question (not sensible IMO)
int year = date % 100;
int month = (date / 100) % 100;
int day = date / 10000;
(Do you have to store your data like this to start with? Ick.)
Storing a date as an integer like this isn't ideal, but if you must do it -- and you're sure that the number will always use the specified format -- then you can easily extract the day, month and year:
int day = date / 10000;
int month = (date / 100) % 100;
int year = date % 100;
You can do this with modular arithmetic:
int day = date / 10000;
int month = (date / 100) % 100;
int year = date % 100;
Here is the solution in Java with no optimization:
final int value = 111213;
int day;
int month;
int year;
day = value / 10000;
month = (value - (day * 10000)) / 100;
year = (value - (day * 10000)) - month * 100;