Hello Everyone I have some interesting situation.
I want to count how many hours (in minutes) is from 20:00 to 01:00 AM, but i Don't know how, because what i have done is:
pabaigosLaikoLaukelis = 01:00;
pradziosLaikoLaukelis = 20:00;
TimeSpan dt = Convert.ToDateTime(pabaigosLaikoLaukelis)- Convert.ToDateTime(pradziosLaikoLaukelis);
int minutes = (int)dt.TotalMinutes;
And i get result -> -1140 minutes, but I need that answer to be just 5 hours from 20:00 to 01:00.
I know that it is quite easy, but i have no idea how to do it.
you could do something like this
//Datetime(Year,month,day,hour,min,sec)
DateTime date1 = new DateTime(2012, 1, 1, 20, 0, 0);
DateTime date2 = new DateTime(2012, 1, 2, 1, 0, 0);
string minutes = (date2.Subtract(date1).TotalMinutes).ToString();
Tested and works 300 minutes (5 hours)
Use full date time strings that contain day part, to show that 01:00 AM is one day later than 20:00 - like following:
int minutes = Convert.ToDateTime("01/02/2012 01:00").Substract(Convert.ToDateTime("01/01/2012 20:00")).TotalMinutes;
You need to specify the Day, you are subracting (Today 1:00 AM) - (Today 8:00 PM)
I think you need to subract (Tommorrow 1:00 AM) - (Today 8:00 PM)
Be careful with adding one day to the endTime, because then the difference between 20:00 and 22:00 will be 26 hours instead of 2!
Just check whether the difference is positive (same day) or negative (next day)
string pabaigosLaikoLaukelis = "01:00";
string pradziosLaikoLaukelis = "20:00";
// This should be 5 hours
TimeSpan dt = Convert.ToDateTime(pabaigosLaikoLaukelis) - Convert.ToDateTime(pradziosLaikoLaukelis);
int hours = (int)dt.TotalHours;
hours = hours < 0 ? 24 + hours : hours;
// This should be 19 hours
dt = Convert.ToDateTime(pradziosLaikoLaukelis) - Convert.ToDateTime(pabaigosLaikoLaukelis);
hours = (int)dt.TotalHours;
hours = hours < 0 ? 24 + hours : hours;
A bit of preparation of the two string variables is required before attempting data calculations
string pabaigosLaikoLaukelis = "01:00";
string pradziosLaikoLaukelis = "20:00";
pabaigosLaikoLaukelis = DateTime.Today.ToString("dd/MM/yyyy") + " " + pabaigosLaikoLaukelis;
pradziosLaikoLaukelis = DateTime.Today.AddDays(-1).ToString("dd/MM/yyyy") + " " + pradziosLaikoLaukelis;
TimeSpan dt = Convert.ToDateTime(pabaigosLaikoLaukelis) - Convert.ToDateTime(pradziosLaikoLaukelis);
Console.WriteLine("{0:D2}:{1:D2}", dt.Hours, dt.Minutes);
You need to add a day to the first TimeSpan and use TotalHours.
var pabaigosLaikoLaukelis = "01:00";
var pradziosLaikoLaukelis = "20:00";
var oneDayTimeSpan = new TimeSpan(1, 0, 0, 0);
TimeSpan dt = TimeSpan.Parse(pabaigosLaikoLaukelis).Add(oneDayTimeSpan) - TimeSpan.Parse(pradziosLaikoLaukelis);
int minutes = (int)dt.TotalHours; // 5 hours
Using associative operations:
var pabaigosLaikoLaukelis = "21:00";
var pradziosLaikoLaukelis = "20:00";
var leftHours = (int)TimeSpan.Parse(pabaigosLaikoLaukelis).TotalHours;
var rightHours = (int)TimeSpan.Parse(pradziosLaikoLaukelis).TotalHours;
// Now we do a Modulus operation which will assure
// 23 > hours > 0
// Make sure to check that leftHours != 0 or rightHours != 0
int hours = (Math.Abs(leftHours * rightHours) + leftHours) % rightHours; //Modulus
var hoursTimeSpan = TimeSpan.FromHours(hours);
How about this:
pabaigosLaikoLaukelis = 01:00;
pradziosLaikoLaukelis = 20:00;
TimeSpan startTime = Convert.ToDateTime(pradziosLaikoLaukelis).TimeOfDay;
TimeSpan endTime = Convert.ToDateTime(pabaigosLaikoLaukelis).TimeOfDay;
TimeSpan diff = endTime > startTime ? endTime - startTime : endTime - startTime + TimeSpan.FromDays(1);
int minutes = (int)diff.TotalMinutes;
Related
I am trying to generate a start and end date time from last week.
so if today is 04/02/2022 then I need a random date and time from last week so it could be
Start 02/02/2022 10:00
End 02/02/2022 10:30
notice that the end time is 30 mins always.
I can get the date part working by using this
Random gen = new Random();
var start = DateTime.Now.AddDays(-7);
int range = (DateTime.Today - DateTime.Today.AddDays(-7)).Days;
var result = start.AddDays(gen.Next(range));
This should work:
Random gen = new Random();
var start = DateTime.Now.AddDays(-7);
start = start.AddDays(gen.Next(6)); // Add 0-6 days
start = start.AddHours(gen.Next(23)); // Add 0-23 hours
start = start.AddMinutes(gen.Next(1)); //Add 0-1 minutes.
var result = new DateTime(
start.Year,
start.Month,
start.Day,
start.Hour,
start.Minute % 2 == 0 ? 0 : 30, // If even then zero, if odd then 30.
0); // 0 seconds
That's kind of a fun challenge. Personally I like simple solutions:
var halfHoursPrWeek = 7 * 24 * 2;
// Get last full hour; ex: 04.02.2022 15:00:00
var previousHour = DateTime.Today.AddHours(DateTime.Now.Hour);
var randomNrOfHalfHours = (new Random()).Next(halfHoursPrWeek);
// ex: 31.01.2022 20:30:00
var sometimeLastWeek = previousHour.AddMinutes(-randomNrOfHalfHours * 30);
As I said in the comment already, generate a DateTime object based on the ticks.
//startDate 7 days ago, without time so 00:00:00
var startDate = DateTime.Now.Date.AddDays(-7);
//endDate with the time of 23:59:59
//notice manipulating the time this way could lead to a DateTime in the future, if you don't want that only use `DateTime.Now`
var endDate = DateTime.Now.Date.AddDays(1).AddMilliseconds(-1);
//ticks in range of the dateTimes
var ticks = new Random().NextInt64(startDate.Ticks, endDate.Ticks);
//new DateTime
var newDate = new DateTime(ticks);
Console.WriteLine($"NewDate in the range of {startDate} and {endDate}:");
Console.WriteLine(newDate);
https://dotnetfiddle.net/HcyAUD
See following :
const int MINUTES_PER_WEEK = 7 * 24 * 60;
DateTime date = DateTime.Now;
DateTime SundayMidnight = date.AddDays(-(int)date.DayOfWeek).Date;
DateTime startDate = SundayMidnight.AddDays(-7);
Random rand = new Random();
int randomMinutes = rand.Next(MINUTES_PER_WEEK - 30);
DateTime randomStartDate = startDate.AddMinutes(randomMinutes);
DateTime randomEndDate = startDate.AddMinutes(randomMinutes + 30);
Calculation through ticks.
// One week interval in ticks.
const long WEEK = 6048000000000;
// Initial date & time.
DateTime now = DateTime.Now;
// Random decrease interval of 1 week.
Random gen = new Random();
long reduce = Convert.ToInt64(gen.NextDouble() * WEEK);
TimeSpan span = TimeSpan.FromTicks(reduce);
// Determine a random date at last week.
DateTime lastWeek = now - span;
This approach is based on precalculating a time interval from zero to 1 week, and then subtracting this period from the current date, while some other methods first subtract a week and then add a random value within a week, which in my opinion is redundant calculations.
How do I get built-up start hours and end hours that if a user just wants to have done several tasks eg every Monday from 08 to 11 the next x number of weeks.
So how can I just do it in a smart way.
I have MoreAdd which tells how many weeks ahead it should make that way.
When I just create a single task. Then it looks like this.
var sTimer = model.StartTime;
var eTimer = model.EndTime;
SignUpInfo addSignUpInfo = new SignUpInfo
{
CompanyId = companyId,
Title = model.Title,
Info = model.Info,
StartTime = sTimer,
EndTimer = eTimer,
Closed = false,
Pay = PayValue,
TaskDone = false,
CreateTime = DateTime.Now,
CategoriId = model.SelectedKategori
};
_db.SignUpInfo.Add(addSignUpInfo);
_db.SaveChanges();
But how will I only do that if I write 5 then make it one from the next Monday and 5 times forward.
I guess you are struggling with determining the start- and end DateTimes for the next 5 weeks from the next Monday. You could use this method:
static IEnumerable<(DateTime start, DateTime end)> GetTimes(DateTime startTime, DateTime endTime, DayOfWeek startDay, int countWeeks)
{
if(endTime < startTime) throw new ArgumentException("TODO");
TimeSpan diff = endTime - startTime;
int daysUntilWeekDay = ((int) startDay - (int) startTime.DayOfWeek + 7) % 7;
DateTime beginningDate = startTime.AddDays(daysUntilWeekDay);
for (int i = 0; i <= countWeeks; i++)
{
DateTime date = beginningDate.AddDays(7 * i);
yield return (start: date, end:date.Add(diff));
}
}
Example:
DateTime dt = new DateTime(2019, 01, 20, 8, 0, 0); //yesterday, sunday, 8 o clock in the morning
foreach(var x in GetTimes(dt, dt.AddHours(3), DayOfWeek.Monday, 5))
Console.WriteLine("Start:{0} End:{1}", x.start, x.end);
With this method it's easy to build a loop that uses your existing code to save the tasks.
I have a Google API that takes date and time and sets up a event in customers calendar and the problem is I am using date time to add hours to the event when I boot time for 12pm noon For whatever reason, it will be listed in my Google Calendar for the day after at 12am.
Here is the code that sets up the date and the time:
// dd is a drop down for hours 1 to 12 Central Time Zone
int iHour = Convert.ToInt32(dd.SelectedItem.Text);
// and this is the minutes values of 30 or 45
int iMinute = Convert.ToInt32(ddMinute.SelectedItem.Text);
var date = "Nov 19, 2017";
DateTime dt = new DateTime();
dt = Convert.ToDateTime(date);
// If its PM set 12 hours more to it because its a 24 hours clock
if (ddAptAmPm.SelectedValue == "PM")
iHour += 12;
dt = dt.AddHours(iHour);
dt = dt.AddMinutes(iMinute);
var startDate = dt;
var endDate = dt;
string sNotes = "TestingA PI";
string sTitle = "Testas" + " with: " + "ASP.NEt" + " " + "Last Name here";
int length = Convert.ToInt32("30");
endDate = endDate.AddMinutes(length);
var google = new GoogleCalendar();
int value = google.CreateCalendarEvent("email", startDate, endDate, sNotes, sTitle);
Can any one see where did I do this wrong
if (ddAptAmPm.SelectedValue == "PM") // If its PM set 12 hours more to it because its a 24 hours clock
iHour += 12;
should be:
if (ddAptAmPm.SelectedValue == "PM" && iHour < 12) // If its 1-11 PM set 12 hours more to it because its a 24 hours clock
iHour += 12;
else if (ddAptAmPm.SelectedValue == "AM" && iHour == 12)
iHour = 0;
Since 12 + 12 is 24, and today plus 24 hours is the next day.
Another way to write it:
if (iHour == 12) // 12 is **before** 1
iHour = 0;
if (ddAptAmPm.SelectedValue == "PM") // If its PM set 12 hours more to it because its a 24 hours clock
iHour += 12;
Another way you could do it is to construct a date string in a specific format (including the AM or PM designation), and then use DateTime.ParseExact to create your startDate. This way you don't have to do all the conversion from string to int, then add 12 hours if PM was specified, etc.
For example, this code would replace everything you currently have up to and including the startDate assignment:
// This assumes that ddAptAmPm.SelectedValue will be "AM" or "PM"
var dateString = string.Format("Nov 19, 2017 {0}:{1} {2}", dd.SelectedItem.Text,
ddMinute.SelectedItem.Text, ddAptAmPm.SelectedValue);
// In a format string, tt is a placeholder for AM/PM
var startDate = DateTime.ParseExact(dateString, "MMM dd, yyyy h:m tt",
CultureInfo.InvariantCulture);
You can read more about Date and Time Format Strings here.
I find the number of days between the date of the employee's employment and the date of the day, and multiply by the daily amount. The only complaint is that when I find out the number of days between two dates, it calculates over 31 days for the months that draw 31 days naturally. I need to trade over 30 days while I get the dates between two dates.
How can I do that?
Do you want something like this?
DateTime date1 = new DateTime(2016, 10, 3);
DateTime date2 = new DateTime(2016, 11, 3);
var numberOfDays = date2.Subtract(date1).TotalDays;
I Hope this is what you wanted:
DateTime firstDay = DateTime.ParseExact("2016-10-03", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
DateTime lastDate = DateTime.ParseExact("2016-11-03", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
double daysBetween = (lastDate - firstDay).TotalDays;
if you are just interested in full month, you can use following code
var normalisedDays = ((lastDate.Year - firstDate.Year) * 12 + lastDate.Month - firstDate.Month) * 30;
in Controll :
DateTime Date_1 = Date_Start;
DateTime Date_2 = Date_End;
TimeSpan difference = Date_2 - Date_1 ;
var days = difference.TotalDays;
in Script :
<script>
function calculateDifference()
{
var Date_Start= document.getElementById("Date_Start").value;
var Date_End= document.getElementById("Date_End").value;
var Date_StartSplit = Date_Start.split("/");
var Date_EndSplit = Date_End.split("/");
var StartDate = new Date(Date_StartSplit[2], Date_StartSplit[0] - 1, Date_StartSplit[1]);
var EndDate = new Date(Date_EndSplit[2], Date_EndSplit[0] - 1, Date_EndSplit[1]);
var res = Math.abs(StartDate - EndDate) / 1000;
var days = Math.floor(res / 86400);
document.getElementById("Nombre_days").value = days;
}
</script>
I am trying to shift a date by a number of given months, but also to keep the same day (for example, if the day of the date is Monday, and after shifting with x months the day is Thursday, I want also to subtract 3 days from the new obtained date. This algorithm should add/subtract days depending on the new obtained date, basically providing the closest date that represents the same day of week). As an example, if I have the start date 10.08.2016(Wednesday), and I add 3 months, I will get 10.11.2016(Thursday), so the closest Wednesday to that day is 09.11.2016.
What I managed to make till now looks something like this:
int startDayOfWeek = ((int)startDay.DayOfWeek) == 0 ? 7 : (int)startDay.DayOfWeek;
int newStartDayOfWeek = ((int)startDay.AddMonths(period).DayOfWeek) == 0 ? 7 : (int)startDay.AddMonths(period).DayOfWeek;
int shiftingDays = startDayOfWeek - newStartDayOfWeek;
if (shiftingDays > 3)
shiftingDays -= 7;
where startDay is the start date, and period is the number of months I want to shift to.
But this still fails some times, so any tips would be greately appreciated.
An example when this code fails would be:
startDate = 01.08.2016 (Monday) and period would be 5
After adding 5 months, I get 01.01.2017, which is Sunday, and the closest Monday would be on 02.01.2017, but I get -6 days.
Use this code. The idea is to divide the days by 7, round it, and multiply by 7.
DateTime endDate = startDay.AddMonths((int)period);
endDate = startDay.AddDays((int)Math.Round((double)(endDate - startDay ).Days / 7)*7);
Is that what you are looking for ?
static void Main( string[] args )
{
//DateTime startDay = DateTime.Now;
DateTime startDay = new DateTime( 2016, 8, 1 );
//DateTime startDay = new DateTime( 2016, 8, 10 );
DateTime newDay = startDay.AddMonths( 5 );
int startDayOfWeek = (int)startDay.DayOfWeek;
int newDayOfWeek = (int)newDay.DayOfWeek;
int shift1 = (7 + startDayOfWeek - newDayOfWeek) % 7;
int shift2 = (7 + newDayOfWeek - startDayOfWeek) % 7;
DateTime test = newDay + ((shift1 > shift2) ? - TimeSpan.FromDays( shift2 ) : TimeSpan.FromDays( shift1 ));
}