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.
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 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 can I get the date of next coming Monday or next coming Friday in C#.
lets say today is Wednesday and I want to get date of coming Friday.
This is what I've done
DateTime time = DateTime.Now.Date;
DateTime NextFriday;
if (time.DayOfWeek == DayOfWeek.Wednesday)
{
NextFriday = DateTime.Now.AddDays(2);
}
with this approach I've to initiate 7 variables for each day and 7 conditions for ever day to find the next specific day.
Is there any better and clean code by which I can get the date of any of the next coming day.
Using the following
public int CalculateOffset(DayOfWeek current, DayOfWeek desired) {
// f( c, d ) = [7 - (c - d)] mod 7
// f( c, d ) = [7 - c + d] mod 7
// c is current day of week and 0 <= c < 7
// d is desired day of the week and 0 <= d < 7
int c = (int)current;
int d = (int)desired;
int offset = (7 - c + d) % 7;
return offset == 0 ? 7 : offset;
}
You can calculate how far you are from the desired day and then add that to the current date
DateTime now = DateTime.Now.Date;
int offset = CalculateOffset(now.DayOfWeek, DayOfWeek.Friday);
DateTime nextFriday = now.AddDays(offset);
DateTime today = DateTime.Today;
DateTime nextFriday = System.Linq.Enumerable.Range(0, 6)
.Select(i => today.AddDays(i))
.Single(day => day.DayOfWeek == DayOfWeek.Friday);
You should probably use a time library that supports this, such as NodaTime.
See date.Next(IsoDayOfWeek.Sunday) on https://nodatime.org/1.3.x/userguide/arithmetic
Here's an alternative solution (please don't use this):
DateTime F(DateTime t, DayOfWeek dayOfWeek) => t.AddDays((7 + (int)dayOfWeek - (int)t.DayOfWeek) % 7);
for (int i = 0; i < 7; i++)
Console.WriteLine((DayOfWeek)i + " " + F(DateTime.Now, (DayOfWeek)i));
Outputs (on Wednesday 4/25/2018):
Sunday 4/29/2018 12:00:00 AM
Monday 4/30/2018 12:00:00 AM
Tuesday 5/1/2018 12:00:00 AM
Wednesday 4/25/2018 12:00:00 AM
Thursday 4/26/2018 12:00:00 AM
Friday 4/27/2018 12:00:00 AM
Saturday 4/28/2018 12:00:00 AM
DayOfWeek is just an enum between 0 and 6, so with modular arithmetic you can use the difference between your date of interest and target day of week to compute the number of days you must add.
A quick warning, you need to take into account timezone of interest when you ask what is meant by "today". It means a different thing depending on which side of the date line you live.
using System;
public class Program
{
public static DateTime NextDayForDay(DayOfWeek dayOfWeek, DateTime occurringAfter)
{
return occurringAfter.AddDays(((dayOfWeek - occurringAfter.DayOfWeek + 6) % 7)+1);
}
public static void Main()
{
for (int i=0; i < 7; i++)
{
for (int j=0; j < 7; j++)
{
DayOfWeek dayOfWeek = (DayOfWeek)(((int)DayOfWeek.Sunday + j) % 7);
DateTime test = DateTime.Today.AddDays(i);
Console.WriteLine($"{test}=>Next {dayOfWeek} is {NextDayForDay(dayOfWeek, test)}");
}
}
}
}
So was looking to see how to code a calendar in C# which is easy if your using asp.net. However, I'm using console application because i'm required to do so. Now coding for a one month was not to bad but I can't figure out how to code a whole year (January-December).
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
int current = 0;
int skip = 0;
int day = 1;
int endDay = 31;
string line = " Sun Mon Tue Wed Thu Fri Sat";
Console.WriteLine(line);
line = "";
while (skip < current)
{
line += " ";
skip++;
}
while (day <= endDay)
{
while (current < 7 && day <= endDay)
{
line += String.Format("{0,4}", day);
current++;
day++;
}
Console.WriteLine(line);
line = "";
current = 0;
}
Console.ReadLine();
}
}
}
after doing so this will display a one month calendar so the question is how could I display a full year calendar while still using console application and from the codes I already have?
You could do something like this. I tried to add comments for explanation:
static void Main(string[] args)
{
// Loop 12 times (once for each month)
for (int i = 1; i < 13; i++)
{
// Get the first day of the current month
var month = new DateTime(2017, i, 1);
// Print out the month, year, and the days of the week
// headingSpaces is calculated to align the year to the right side
var headingSpaces = new string(' ', 16 - month.ToString("MMMM").Length);
Console.WriteLine($"{month.ToString("MMMM")}{headingSpaces}{month.Year}");
Console.WriteLine(new string('-', 20));
Console.WriteLine("Su Mo Tu We Th Fr Sa");
// Get the number of days we need to leave blank at the
// start of the week.
var padLeftDays = (int)month.DayOfWeek;
var currentDay = month;
// Print out the day portion of each day of the month
// iterations is the number of times we loop, which is the number
// of days in the month plus the number of days we pad at the beginning
var iterations = DateTime.DaysInMonth(month.Year, month.Month) + padLeftDays;
for (int j = 0; j < iterations; j++)
{
// Pad the first week with empty spaces if needed
if (j < padLeftDays)
{
Console.Write(" ");
}
else
{
// Write the day - pad left adds a space before single digit days
Console.Write($"{currentDay.Day.ToString().PadLeft(2, ' ')} ");
// If we've reached the end of a week, start a new line
if ((j + 1) % 7 == 0)
{
Console.WriteLine();
}
// Increment our 'currentDay' to the next day
currentDay = currentDay.AddDays(1);
}
}
// Put a blank space between months
Console.WriteLine("\n");
}
Console.Write("\nDone!\nPress and key to exit...");
Console.ReadKey();
}
Output:
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;