Scheduling should not accept 1 hour before a scheduled time - c#

I am making a scheduling system using VS2012 and SQLSERVER2012
I already validated that if the desired schedule day and time is already taken it will not submit.
This is the code
string sqlString = "Select [Date],[StartTime],[EndTime] FROM tbl_Schedule where [Date] ='" + txtDate.Value.ToShortDateString() + "' AND [StartTime] = '"+txtStart.Text+"' AND [EndTime] = '"+txtEnd.Text+"' ;";
How can I determine if my desired scheduled time is 1hr before the existing scheduled time.

string desiredTime = "10/10/2017 09:18";
DateTime d = DateTime.Parse(desiredTime);
string existingTime = "10/10/2017 10:18";
DateTime e = DateTime.Parse(existingTime);
if ((e-d).Hours <= 1)
{
Console.WriteLine("true");
}
(Datetime e - DateTime d) will give you a TimeSpan object, then you just check the hours on that to see if it's less than or equal to 1.

string desiredTime = "10/10/2017 09:18";
DateTime d = DateTime.Parse(desiredTime);
string existingTime = "10/10/2017 10:18";
DateTime e = DateTime.Parse(existingTime);
if (e.Hour - d.Hour == 1)
{
Console.WriteLine("true");
}

Related

Time where minutes are not counted in a C# assertion snippet for an appium test

I am attempting to ensure that hours are not off minutes I am not too concerned with but can't seem to break them off the code. Is there a way to allow the assertion to be 10 minutes off?
public void DeviceTimeAssertion()
{
IWebElement TimeTitle = _driver.FindElementByXPath("
(//android.widget.TextView[#content-desc='xpathvalue'])[1]");
string Time = DateTime.Now.ToString("MM/dd/yy h:mm tt");
//string Time = DateTime.Now.ToString("MM/dd/yy h:mm");
string ActText = TimeTitle.Text;
string ExpectedTime = "Check-in: " + Time;
//if (ExpText.Equals(ActText))
Assert.AreEqual(ExpectedTime, ActText);
I think you need to do that with actual DateTime objects. You can try to do that:
var time = DateTime.Now;
var actText = TimeTitle.Text;
var isTime = DateTime.TryParse(actText.Split(' ')[1], out var actTime)
if(isTime)
{
var diff = TimeSpan.FromMinutes(10);
Assert.IsTrue(time + diff > actTime && time - diff < actTime);
}
else
{
throw new ArgumentException("There was no Time in the text :(");
}
Hope that helps

Check if less than 7 days before ending [duplicate]

I see that this question has been answered for Java, JavaScript, and PHP, but not C#. So, how might one calculate the number of days between two dates in C#?
Assuming StartDate and EndDate are of type DateTime:
(EndDate - StartDate).TotalDays
The top answer is correct, however if you would like only WHOLE days as an int and are happy to forgo the time component of the date then consider:
(EndDate.Date - StartDate.Date).Days
Again assuming StartDate and EndDate are of type DateTime.
Use TimeSpan object which is the result of date substraction:
DateTime d1;
DateTime d2;
return (d1 - d2).TotalDays;
I think this will do what you want:
DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(-1);
TimeSpan t = d1 - d2;
double NrOfDays = t.TotalDays;
DateTime xmas = new DateTime(2009, 12, 25);
double daysUntilChristmas = xmas.Subtract(DateTime.Today).TotalDays;
// Difference in days, hours, and minutes.
TimeSpan ts = EndDate - StartDate;
// Difference in days.
int differenceInDays = ts.Days; // This is in int
double differenceInDays= ts.TotalDays; // This is in double
// Difference in Hours.
int differenceInHours = ts.Hours; // This is in int
double differenceInHours= ts.TotalHours; // This is in double
// Difference in Minutes.
int differenceInMinutes = ts.Minutes; // This is in int
double differenceInMinutes= ts.TotalMinutes; // This is in double
You can also get the difference in seconds, milliseconds and ticks.
In case someone wants numer of whole days as a double (a, b of type DateTime):
(a.Date - b.Date).TotalDays
There often is a debate on time (hours) when it comes to counting days between two dates. The responses to the question and their comments show no exception.
Considering StartDate and EndDate are of type DateTime: if performance is not a concern, I would strongly recommend documenting your calculation through intermediate conversions. For example, (EndDate - StartDate).Days is unintuitive because rounding will depend on the hour component of StartDate and EndDate.
If you want the duration in days to include fractions of days, then as already suggested
use (EndDate - StartDate).TotalDays.
If you want the duration to reflect
the distance between two days, then use (EndDate.Date - StartDate.Date).Days
If you want the duration to reflect the
duration between the morning of the start date, and the evening of
the end date (what you typically see in project management software), then use
(EndDate.Date - StartDate.Date).Days + 1
You can try this
EndDate.Date.Subtract(DateTime.Now.Date).Days
Using a timespan would solve the problems as it has many attributes:
DateTime strt_date = DateTime.Now;
DateTime end_date = Convert.ToDateTime("10/1/2017 23:59:59");
//DateTime add_days = end_date.AddDays(1);
TimeSpan nod = (end_date - strt_date);
Console.WriteLine(strt_date + "" + end_date + "" + "" + nod.TotalHours + "");
Console.ReadKey();
For a and b as two DateTime types:
DateTime d = DateTime.Now;
DateTime c = DateTime.Now;
c = d.AddDays(145);
string cc;
Console.WriteLine(d);
Console.WriteLine(c);
var t = (c - d).Days;
Console.WriteLine(t);
cc = Console.ReadLine();
For beginners like me that will stumble upon this tiny problem, in a simple line, with sample conversion to int:
int totalDays = Convert.ToInt32((DateTime.UtcNow.Date - myDateTime.Date).TotalDays);
This calculates the total days from today (DateTime.UtcNow.Date) to a desired date (myDateTime.Date).
If myDateTime is yesterday, or older date than today, this will give a positive (+) integer result.
On the other side, if the myDateTime is tomorrow or on the future date, this will give a negative (-) integer result due to rules of addition.
Happy coding! ^_^
First declare a class that will return later:
public void date()
{
Datetime startdate;
Datetime enddate;
Timespan remaindate;
startdate = DateTime.Parse(txtstartdate.Text).Date;
enddate = DateTime.Parse(txtenddate.Text).Date;
remaindate = enddate - startdate;
if (remaindate != null)
{
lblmsg.Text = "you have left with " + remaindate.TotalDays + "days.";
}
else
{
lblmsg.Text = "correct your code again.";
}
}
protected void btncal_Click(object sender, EventArgs e)
{
date();
}
Use a button control to call the above class. Here is an example:
You can use the code below:
int DateDifInSecond = EndDate.Subtract(StartDate).TotalSeconds
Get the difference between the two dates and then get the days from:
int total_days = (EndDate - StartDate).TotalDays
try this truly worked Get actual days diff. date format is "dd/MM/yyyy"
string[] d1 = txtFromDate.Values.Split('/');
string[] d2 = txtToDate.Values.Split('/');
DateTime FrmDt = new DateTime(Convert.ToInt32(d1[2]), Convert.ToInt32(d1[1]), Convert.ToInt32(d1[0]));
DateTime ToDt = new DateTime(Convert.ToInt32(d2[2]), Convert.ToInt32(d2[1]), Convert.ToInt32(d2[0]));
TimeSpan TDiff = ToDt.Subtract(FrmDt);
String DaysDiff = TDiff.TotalDays.ToString();
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
DateTime d = Calendar1.SelectedDate;
// int a;
TextBox2.Text = d.ToShortDateString();
string s = Convert.ToDateTime(TextBox2.Text).ToShortDateString();
string s1 = Convert.ToDateTime(Label7.Text).ToShortDateString();
DateTime dt = Convert.ToDateTime(s).Date;
DateTime dt1 = Convert.ToDateTime(s1).Date;
if (dt <= dt1)
{
Response.Write("<script>alert(' Not a valid Date to extend warranty')</script>");
}
else
{
string diff = dt.Subtract(dt1).ToString();
Response.Write(diff);
Label18.Text = diff;
Session["diff"] = Label18.Text;
}
}

calculate difference between two dates using c#

I'm trying to calculate difference between two dates, my code is given below
DateTime daterenew = DateTime.Parse(drow.ItemArray.GetValue(16).ToString()); //18/01/2017
DateTime datecurrent = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy"));
renewstatuslbl.Text = ((daterenew - datecurrent).Days) + " Day(s) remains";
But I'm getting an error
"String was not recognized as a valid DateTime."
I would simplify that:
var daterenew = DateTime.ParseExact("18/01/2017", "dd/MM/yyyy", CultureInfo.InvariantCulture);
var res = ((daterenew - DateTime.Today).Days) + " Day(s) remains";
Note, that DateTime.Now != DateTime.Today.
Try something like this
string dateString = drow.ItemArray.GetValue(16).ToString();
DateTime daterenew = DateTime.ParseExact(dateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
renewstatuslbl.Text = string.Format("{0} Day(s) remains", (daterenew - DateTime.Now).TotalDays);
Idea is in ParseExact where you can set up format for your date in drow.ItemArray
Also look at TotalDays
Assuming your drow.ItemArray.GetValue(16).ToString()format is always dd/MM/yyyy. Use ParseExact
DateTime daterenew = DateTime.ParseExact(drow.ItemArray.GetValue(16).ToString(), "dd/MM/yyyy", null); //18/01/2017
//DateTime datecurrent = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy"));
DateTime datecurrent = DateTime.Now;
renewstatuslbl.Text = ((daterenew - datecurrent).Days) + " Day(s) remains";
The format of the date , causes the error. 18/01/2017
https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
example I used "yyyy/MM/dd"
//DateTime daterenew = DateTime.Parse("18/01/2017"); //18/01/2017
DateTime daterenew = DateTime.Parse("2017.01.18"); //18/01/2017
DateTime datecurrent = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy"));
object renewstatuslbl = ((daterenew - datecurrent).Days) + " Day(s) remains";
thus, I think you can change the string date format first of the value before inserting to drow.ItemArray
enter codenamespace FineCalculation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DateTime date01 = date1.Value;
DateTime date02 = date2.Value;
TimeSpan timeSpan = date02 - date01;
int days = Convert.ToInt16(timeSpan.TotalDays);
double fine = 0;
if(days < 30)
{
fine = days * 0.5;
}else if(days > 30 && days < 60)
{
fine = days * 0.5 * 0.75;
}else if(days > 60)
{
fine = days * 0.5 * 0.75 * 1;
}
MessageBox.Show("For "+ days + " days fine is " + fine.ToString());
}
}
} here

How To Display Date In Locale For 0 Values?

Ok, so I have a date stored in UK format (dd/mm/yy) which I need to display in the locale of wherever the user might be.
The issue is that this date can be 000000 (00/00/2000); so I can't convert it to DateTime directly, as DateTime doesn't support 0 values for day or month.
I have this so far:
int dateInt = ddmmyy;
var year = (dateInt % 100) + 2000;
var month = (dateInt / 100) % 100;
var day = (dateInt / 100000);
var result = new DateTime(year, month, day); //2014/00/00 at this point, so breaks.
var resultStr = result.ToString(CultureInfo.InvariantCulture);
return resultStr;
What's the correct way to add support for 0 values initially? I've tried changing the 0 to 1 before converting to DateTime, running the conversion and then replacing with a 0 again; but due to culture variants I see no way that this method can support other cultures, which is the purpose of this conversion to begin with.
Any ideas? I'm guessing this is a common issue.
Is this what you need ?
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int[] savedDates = new int[] { 000000, 010000, 000013 };
foreach (var item in savedDates)
{
DateTime date = ConvertToDate(item);
Console.WriteLine(item.ToString("D6") + " => " + date.ToShortDateString());
}
Console.ReadLine();
}
private static DateTime ConvertToDate(int item)
{
string temp = item.ToString("D6");
int day = int.Parse(temp.Substring(0, 2));
int month = int.Parse(temp.Substring(2, 2));
int year = int.Parse(temp.Substring(4, 2));
if (day == 0)
day = 1;
if (month == 0)
month = 1;
year += 2000;
return new DateTime(year, month, day);
}
}
}
I would not store dates like this as the methodology for doing so is already provided by the .NET framework.
The best way to store dates would be to use Culture.InvariantCulture for string conversion cases and then convert to local culture for display purposes as necessary. DateTime itself is culture-independent so converting between cultures is very easy.

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

I have a need to convert a string value in the form "YYYYMMDDHHMMSS" to a DateTime. But not sure on how, may be a DateTime.Tryparse can be used to make this happen. Or is there any other way to do it. I can do this using some string operations to take "YYYYMMDD" alone, convert to a datetime and then add HH, MM, SS separately to that DateTime. But is there any DateTime.TryParse() methods that I can use in one line to convert a "YYYYMMDDHHMMSS" format string value to a DateTime value?
Define your own parse format string to use.
string formatString = "yyyyMMddHHmmss";
string sample = "20100611221912";
DateTime dt = DateTime.ParseExact(sample,formatString,null);
In case you got a datetime having milliseconds, use the following formatString
string format = "yyyyMMddHHmmssfff"
string dateTime = "20140123205803252";
DateTime.ParseExact(dateTime ,format,CultureInfo.InvariantCulture);
Thanks
You have to use a custom parsing string. I also suggest to include the invariant culture to identify that this format does not relate to any culture. Plus, it will prevent a warning in some code analysis tools.
var date = DateTime.ParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
class Program
{
static void Main(string[] args)
{
int transactionDate = 20201010;
int? transactionTime = 210000;
var agreementDate = DateTime.Today;
var previousDate = agreementDate.AddDays(-1);
var agreementHour = 22;
var agreementMinute = 0;
var agreementSecond = 0;
var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);
DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));
Console.WriteLine("Selected Date : " + selectedDate.ToString());
Console.WriteLine("Start Date : " + startDate.ToString());
Console.WriteLine("End Date : " + endDate.ToString());
if (selectedDate > startDate && selectedDate <= endDate)
Console.WriteLine("Between two dates..");
else if (selectedDate <= startDate)
Console.WriteLine("Less than or equal to the start date!");
else if (selectedDate > endDate)
Console.WriteLine("Greater than end date!");
else
Console.WriteLine("Out of date ranges!");
}
}

Categories

Resources