How to get DateOfBirth using age in c#? - 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;

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.

Int to datetime or timespan to double

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

how can calculate age years and month and day by dateTimePicker ValueChanged c#

I use a DateTimePicker and I use this code to calculate an age:
private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
{
// CurrentYear - BirthDate
int Age = DateTime.Today.Year - dateTimePicker2.Value.Year;
textBox11.Text = Age.ToString();
}
I want to calculate the age by year, month and days when DateTimePicker´s value changes.
In your example it calculate only year, below code will give you year, month and days of age.
CODE:
private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
{
// CurrentYear - BirthDate
DateTime startTime = Convert.ToDateTime(dateTimePicker2.Value);
DateTime endTime = DateTime.Today;
TimeSpan span = endTime.Subtract(startTime);
var totalDays = span.TotalDays;
var totalYears = Math.Truncate(totalDays / 365);
var totalMonths = Math.Truncate((totalDays % 365) / 30);
var remainingDays = Math.Truncate((totalDays % 365) % 30);
textBox11.Text = string.Format("{0} year(s), {1} month(s) and {2} day(s)", totalYears, totalMonths, remainingDays);
}

Get hours between two dates [duplicate]

This question already has answers here:
Determine the difference between two DateTimes, only counting opening hours
(6 answers)
Closed 6 years ago.
I have a C# method like this:
public int GetWorkLogHours(DateTime? startDate, DateTime? endDate, string startTime, string endTime)
{
}
I have a table of Holiday in which all the holidays are saved. What this method supposed to do is to calculate the number of hours between the startDate and startTime to endDate and endTime.It needs to exclude weekends and also skip the holiday between the two dates.
For Example :
We work monday to friday 9:00 AM to 17:00 PM (8 hours). If the
startDate(1-3-2016) and startTime(9:00) and endDate(10-3-2016) and
endTime(13:00). In my Holiday table (8-3-2016) is holiday then it
should return 52 hours
I hope this will solve your problem.
string start = "2016-01-07 09:00:00.000";
string end = "2016-01-07 17:00:00.000";
DateTime firstDay = Convert.ToDateTime(start);
DateTime lastDay = Convert.ToDateTime(end);
if (firstDay > lastDay)
{
}
else
{
TimeSpan span = lastDay - firstDay;
int businessDays = span.Days + 1;
int fullWeekCount = businessDays / 7;
if (businessDays > fullWeekCount * 7)
{
int firstDayOfWeek = (int)firstDay.DayOfWeek;
int lastDayOfWeek = (int)lastDay.DayOfWeek;
if (lastDayOfWeek < firstDayOfWeek)
lastDayOfWeek += 7;
if (firstDayOfWeek <= 6)
{
if (lastDayOfWeek >= 7)
businessDays -= 2;
else if (lastDayOfWeek >= 6)
businessDays -= 1;
}
else if (firstDayOfWeek <= 7 && lastDayOfWeek >= 7)
businessDays -= 1;
}
businessDays -= fullWeekCount + fullWeekCount;
}
double hours = 8 * businessDays;
also if you have an array of holidays like, DateTime[] bankHolidays then you can exclude the holidays also.
// subtract the number of bank holidays during the time interval
foreach (DateTime bankHoliday in bankHolidays)
{
DateTime bh = bankHoliday.Date;
if (firstDay <= bh && bh <= lastDay)
--businessDays;
}

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