Int to datetime or timespan to double - c#

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}");
}
}
}

Related

Get the days of a week given day name

public class Date
{
public int mm;
public int dd;
public Date(int get_mm, int get_dd)
{
mm = get_mm;
dd = get_dd;
}
int day = (int)(daysofweek)Enum.Parse(typeof(daysofweek), DateTime.Now.DayOfWeek.ToString());
for (int i = 1; i < 8; i++)
{
int day_fetch = i - day;
Console.WriteLine(Date date = new Date(DateTime.Now.Month, DateTime.Now.Day + day_fetch));
}
I made this but it doesn't seems working well
What can i do to make it work and how can i solve that problem if the date is for example March 30(The first 2 days is on march but the others are on April)
Try this
// 30 March
var dateTime = DateTime.Now.AddDays(3);
var dayOfWeek = dateTime.DayOfWeek;
// Figure out the first day on the calendar
CultureInfo ci = CultureInfo.CurrentCulture;
Calendar calendar = ci.Calendar;
var firstDayOfWeek = ci.DateTimeFormat.FirstDayOfWeek;
// date (in this case Now) is exlcusive
var daysToBeginningOfWeek = dayOfWeek - firstDayOfWeek;
// Days from beginning of the week to date
for (var i = daysToBeginningOfWeek; i >= 0; i--)
{
var dt = dateTime.AddDays(-i);
Date date = new Date(dt.Month, dt.Day);
Console.WriteLine(date);
}
// Days after date to end of the week
var daysToEndOfWeek = 7 - daysToBeginningOfWeek - 1;
for (var i = 1; i <= daysToEndOfWeek; i++)
{
var dt = dateTime.AddDays(i);
Date date = new Date(dt.Month, dt.Day);
Console.WriteLine(date);
}
You will also need to take first day of the week into consideration because not all calendars are from Sunday to Saturday.

Program for calculating the time before the event starts in days

I wrote a program that calculates the number of days before the event, there may be several events, I would like to know how to reduce or simplify this code.
namespace Determining_the_time_before_the_event_starts
{
class Program
{
struct Event
{
public string name;
public DateTime time;
}
static Event[] InPutEvents()
{
Console.Write("Number of events: ");
int n, year, month, day, hour, min;
n = int.Parse(Console.ReadLine());
Event[] time = new Event[n];
for(int i=0; i<n; i++)
{
Console.Write("Event name: ");
time[i].name = Console.ReadLine();
Console.Write("Event start year: ");
year = int.Parse(Console.ReadLine());
Console.Write("Month of the beginning of the event: ");
month = int.Parse(Console.ReadLine());
Console.Write("The first day of the event: ");
day = int.Parse(Console.ReadLine());
Console.Write("Watch the beginning of the event: ");
hour = int.Parse(Console.ReadLine());
Console.Write("Minutes before the event starts: ");
min = int.Parse(Console.ReadLine());
time[i].time = new DateTime(year, month, day, hour, min, 0);
Console.WriteLine();
}
return time;
}
static void Main(string[] args)
{
Event[] time = InPutEvents();
Console.WriteLine();
BeginEvent(time);
Console.ReadLine();
}
static void BeginEvent (Event[] time)
{
DateTime now = DateTime.Now;
for(int i = 0; i < time.Length; i++)
{
SearchTime(time[i], now);
Console.WriteLine();
}
}
static void SearchTime(Event time, DateTime now)
{
int year, month, day, hour, min;
year = time.time.Year - now.Year;
month = time.time.Month - now.Month;
day = time.time.Day - now.Day;
hour = time.time.Hour - now.Hour;
min = time.time.Minute - now.Minute;
if (min < 0)
{
min += 60;
hour--;
}
if (min > 60)
{
min -= 60;
hour++;
}
if (hour < 0)
{
hour += 24;
day--;
}
if (hour > 24)
{
hour -= 24;
day++;
}
if (day < 1)
{
day += 31;
month--;
}
if (day > 31)
{
day -= 31;
month++;
}
if (month < 1)
{
month += 12;
year--;
}
if (month > 12)
{
month -= 12;
year++;
}
day += (month * 31) + (year * 365);
Console.WriteLine($"Event {time.name} starts in {day} days, {hour}hours, and {min}m. ");
}
}
}
Subtracting a DateTime object from another DateTime Object creates a TimeSpan object. The TimeSpan object has properties like Days, Hours, Minutes and so forth.
Simply use these properties to build the solution you need.
private static void SearchTime(Event event, DateTime now)
{
var diff = event.time - now;
Console.WriteLine($"Event {event.name} starts in {diff.Days} days, {diff.Hours}hours, and {diff.Minutes}m. ");
}

How to get DateOfBirth using age in c#?

I have user age, month and day something like 18 year 2 month and 5 days. I need to return user DateOfBirth using these params. How can I find user DateOfBirth from year, month and day?
I've found a solution and it's works for me.
public static DateTime GetDateOfBirth(int year, int month, int day)
{
var today = DateTime.Today;
int currentYear = today.Year;
int currentDay = today.Day;
int currentMonth = today.Month;
if (day >= currentDay)
{
currentMonth--;
currentDay += DateTime.DaysInMonth(currentYear, currentMonth);
}
if (month >= currentMonth)
{
currentMonth += 12;
currentYear--;
}
return new DateTime(currentYear - year, currentMonth - month, currentDay - day);
}
you can always use AddDays/Months/Years with negative number to actually subtract Days/Months/Years from date.
DateTime now = DateTime.Now;
Console.WriteLine("Today's Date:" + now.ToString());
int years = 18;
int months = 2;
int days = 5;
now = now.AddYears((-1) * years);
now = now.AddMonths((-1) * months);
now = now.AddDays((-1) * days);
Console.WriteLine("Date Of Birth:" + now.ToString());
return now;

How to subtract timestamps using C# [duplicate]

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;

Get Date by passing dayofweek, weekofmonth, monthofyear and year using c#

I need a method which can return a date after taking 4 inputs, dayofweek, weekofmonth, monthofyear and year. I have tried the following but it fails when 4th week of month doesn't have all days, so I return 28 to be at safer side. I would like to have a complete solution and better than this if possible. Please ignore my parameters, I know I can improve it by passing a date instead. Here is my code;
public static DateTime GetDateByDayOfWeekOfMonthOfYear(int dayOfWeek, int weekOfMonth, int monthOfYear, int year)
{
var firstDayOfMonth = new DateTime(year, monthOfYear, 1);
var firstDay = (int)firstDayOfMonth.DayOfWeek;
var addor = 0;
if (firstDay == (int)DayOfWeek.Monday)
addor = 0;
if (firstDay == (int)DayOfWeek.Tuesday)
addor = 6;
if (firstDay == (int)DayOfWeek.Wednesday)
addor = 5;
if (firstDay == (int)DayOfWeek.Thursday)
addor = 4;
if (firstDay == (int)DayOfWeek.Friday)
addor = 3;
if (firstDay == (int)DayOfWeek.Saturday)
addor = 2;
if (firstDay == (int)DayOfWeek.Sunday)
addor = 1;
var resultantDate = firstDayOfMonth.AddDays((7 * weekOfMonth + addor) - (7 - dayOfWeek) - 1);
return resultantDate.Month == monthOfYear
? resultantDate
: firstDayOfMonth.AddDays(27);
}
You can do it this way - for the weekday of your choice, and for the first or a later occurrence of this weekday:
// Select year, month, weekday, and occurrence of weekday.
int year = 2015;
int month = 10;
DayOfWeek dayOfWeek = DayOfWeek.Monday;
int occurrence = 1; // Valid values: 1 to 5.
// Constants.
const int daysInWeek = 7;
const int maximumWeek = 5;
const int minimumWeek = 1;
occurrence = occurrence < minimumWeek ? minimumWeek : occurrence;
occurrence = occurrence > maximumWeek ? maximumWeek : occurrence;
DateTime first = new DateTime(year, month, 1);
int primoOffset = (dayOfWeek - first.DayOfWeek + daysInWeek) % daysInWeek;
DateTime dayInMonth = first.AddDays(primoOffset + daysInWeek * --occurrence);
if (dayInMonth.Month != month)
{
// Week 5 belongs to the next month.
// Return value for the last occurrence.
dayInMonth = dayInMonth.AddDays(-daysInWeek);
}
return dayInMonth;

Categories

Resources