DateTime Setting dates for next day - c#

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.

Related

How to convert Persian date string to Datetime format

Based on the following code, when I receive the hijri (Persian) time string in the method and want to convert it to datetime, the format will be returned to the Gregorian format if I want the hijri (Persian) format to be datetime.
public static DateTime Convert_String_To_DateTime(string PersianDate, string Time)
{
PersianCalendar pc = new PersianCalendar();
int year = Convert.ToInt32(PersianDate.Substring(0, PersianDate.IndexOf('/')));
int month = Convert.ToInt32(PersianDate.Substring(PersianDate.IndexOf('/') + 1, 2));
int day = Convert.ToInt32(PersianDate.Substring(PersianDate.IndexOf('/') + 4, 2));
int hour = Convert.ToInt32(Time.Substring(0, Time.IndexOf(':')));
int min = Convert.ToInt32(Time.Substring(Time.IndexOf(':') + 1));
DateTime ConvertedDate = new DateTime(year, month, day, hour, min, 0, pc);
return ConvertedDate;
}
I am not 100% sure what you want to accomplish but if you want to change the output of your date and time you can use
DateTime dt = DateTime.Now;
string mydate = dt.ToString("dd-MM-yyyy hh:mm:ss");
dd - day
MM - Month short ex. for August you gonna get 08 if you want just 8 use single M and MMM for 3 letters and MMMM for a full month like August
yyyy - Year same rule applies to year as well
hh-Hour
mm-minute
ss secont
you have as well tt that will show you AM/PM
you use from PersianCalendar library and you should solve your problem with this function in that library
Datetime miladiconvert= PersianDateTime.Parse(Yourvariable).ToDateTime();
but you should pass currect format in this parsing so you should this funcation i wrote and use it
public string convertdate(string date)
{
string[] st = new string[3];
st = date.Split('/');
if (int.Parse(st[0]) < 10)//year
{
st[0] = "0" + st[0];
}
if (int.Parse(st[1]) < 10 && st[1].Length == 1)//month
{
st[1] = "0" + st[1];
}
if (int.Parse(st[2]) < 10 && st[2].Length == 1)//day
{
st[2] = "0" + st[2];
}
date = st[0] + "/" + st[1] + "/" + st[2];
return date;
}
Finally if you want add hour and minutes you can use from add
miladiconvert= miladiconvert.AddHours(your Hours)
miladiconvert=miladiconvert.AddMinutes(your Minutes)

How to delete a particular time slot, from the difference between two dates

string StartDateString = "2020-04-20 18:05:07.6187";
DateTime StartDate = DateTime.Parse(StartDateString);
string EndDateString = "2020-04-22 14:10:00.6187";
DateTime EndDate = DateTime.Parse(EndDateString);
TimeSpan DifferenceStartDateEndDate = StartDate - EndDate;
Now I want to delete time between 10 pm to 8am from DifferenceStartDateEndDate (1 day 20 hours four minutes). I.e. I want to remove time between 10 pm to 8 am which will occur from StartDate to EndDate.
As I understand it, you need to add to your calculation only hours in a day during which your business is active. (08:00 - 22:00)
Here are two helpers:
// For the first day in our calculation
// Start at 08:00 if the given date has an hour component that is earlier
static TimeSpan GetTill2200(DateTime date)
{
if (date.Hour >= 22) return TimeSpan.Zero;
if (date.Hour < 8) date = date.Date.AddHours(8);
return date.Date.AddHours(22) - date;
}
// For the last day in our calculation
// End at 22:00 if the given date has an hour component that is later
static TimeSpan GetFrom0800(DateTime date)
{
if (date.Hour < 8) return TimeSpan.Zero;
if (date.Hour >= 22) date = date.Date.AddHours(22);
return date - date.Date.AddHours(8);
}
And here is the code flow to combine start and end dates and the dates in the middle
// StartDate and EndDate variables as in your question.
TimeSpan result = GetTill2200(StartDate);
DateTime currentDate = StartDate.AddDays(1);
while (currentDate.Date < EndDate.Date)
{
// Add 14 hours
// Total: 17:54:52:3813
result = result.Add(TimeSpan.FromHours(14));
currentDate = currentDate.AddDays(1);
}
// returns 06:10:00.6187
// Total = 1.00:04:53 ( 1 days, 4 minutes, 53 seconds )
result = result.Add(GetFrom0800(EndDate));
// Prints 1.00:04:53
Console.WriteLine(result);

Calculate 14 days sequence order

Can anyone please help me, how do I calculate fortnightly (14 days) logic using C#?, for a example 14 days start following sequence order on February
Monday start date 8 Feb (next 22 Feb, 7 March, 21 March etc..)
Thursday start date 11 February (next 25 Feb, 10 March, 24 March etc..)
Friday start date 12 February (next 26 Feb, 11 March, 25 March etc..)
My logic is not working for the 14 days day display, because 15 February will come 14 days add, it’ll display “First14days” date 29 February 2016, it is a wrong.
This is C# logic
Day.Days value are Monday, Thursday, Friday etc..
foreach (var Day in day)
{
Example Day.Days = Monday
Int 14days = (((int)Enum.Parse(typeof(DayOfWeek), Day.Days) - (int)today.DayOfWeek + 14) % 7);
DateTime First14days = today.AddDays(14days);
}
My output should be
Simply add TimeSpan.FromDays(14) to any date to get a fortnight further on
DateTime startDate = DateTime.Now;
TimeSpan fortnight = TimeSpan.FromDays(14);
for (int i = 0; i < 6; i++)
{
startDate += fortnight;
Console.WriteLine($"Date for fortnight {i}: {startDate:D}");
}
If I understand correct your question this code will be working for you.
DateTime time = DateTime.Now;
DateTime anotherTime = DateTime.Now;
var allTimes = new HashSet<DateTime>();
for (int i = 0; i < 6; i++)
{
anotherTime = time.AddDays(14);
time = anotherTime;
Console.WriteLine(anotherTime.ToLongDateString());
allTimes.Add(time);
}
// or with your example is possible to like this code.
foreach (var Day in day)
{
anotherTime = Day.AddDays(14);
time = anotherTime;
Console.WriteLine(anotherTime.ToLongDateString());
allTimes.Add(time);
}
First create two DataTime objects. then foreach few times, and in for loop statement set anotherTime = time.AddDays(14) after that set time = anotherTime.
//Output:
//Saturday, February 27, 2016
//Saturday, March 12, 2016
//Saturday, March 26, 2016
//Saturday, April 09, 2016
//Saturday, April 23, 2016
//Saturday, May 07, 2016
EDIT:
I create and HashSet where you can save all you DateTime who you make it.
So here's you all-in-one solution:
// determine the date of next given weekday
DateTime date = GetNextWeekday(DateTime.Today, DayOfWeek.Tuesday);
// create a list and add the start date (if you want)
List<DateTime> fortnights = new List<DateTime>() { date };
// add as many "fortnights" as you like (e.g. 5)
for (int i = 0; i < 5; i++)
{
date = date.Add(TimeSpan.FromDays(14));
fortnights.Add(date);
}
// use your list (here: just for printing the list in a console app)
foreach (DateTime d in fortnights)
{
Console.WriteLine(d.ToLongDateString());
}
Method to get the next weekday, from:
https://stackoverflow.com/a/6346190/2019384
public static DateTime GetNextWeekday(DateTime start, DayOfWeek day)
{
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysToAdd = ((int) day - (int) start.DayOfWeek + 7) % 7;
return start.AddDays(daysToAdd);
}

C# subtract time (hours minutes)

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;

c# - How do I loop through a time range

I would like to define the start time as 6pm and end time as 9pm. This time range (something looked like below) used for everyday's schedule. How do I implement in for loop? Appreciate for any reply.
6:00 PM
6:30 PM
7:00 PM
7:30 PM
8:00 PM
8:30 PM
9:00 PM
you could use while loop
var startTime = DateTime.Parse("2012-01-28 18:00:00");
var endTime = startTime.AddHours(3);
while (startTime <= endTime)
{
System.Console.WriteLine(startTime.ToShortTimeString());
startTime = startTime.AddMinutes(30);
}
Simple example with TimeSpan:
for (int minutes = 6 * 60; minutes <= 9 * 60; minutes += 30)
{
Console.WriteLine(TimeSpan.FromMinutes(minutes));
}
you can try using DateTime.Now.Hour to get the hour and use if clauses. see exemple below
if (DateTime.Now.Hour >= 9 && DateTime.Now.Hour <= 18) { Console.WriteLine("Bonjour " + Environment.UserName); }
else
{
Console.WriteLine("Bonsoir " + Environment.UserName);
}
if u r going through current date with a time range from like 10:00:00 AM to 17:00:00 PM then u could use the below code
DateTime startTime = DateTime.Parse("10:00:00");
DateTime endTime = DateTime.Parse("17:00:00");
while (startTime <= endTime)
{
System.Console.WriteLine(startTime.ToShortTimeString());
startTime = startTime.AddMinutes(30);
}
When you use TimeSpan (time instead of Time and Date in DateTime)
TimeSpan interval = new TimeSpan(0, 30, 0);
TimeSpan beginTime = new TimeSpan(18, 00, 00);
TimeSpan endTime = new TimeSpan(21, 00, 00);
for(TimeSpan tsLoop = beginTime; tsLoop < endTime; tsLoop = tsLoop.Add(interval))
{
}

Categories

Resources