I'm trying to check if the passing variable date is greater than a static date which I have included in the code and currently trying to use the following code,
private String LastPayDate {
get {
string foo;
if(Parameters.TryGetValue("Last Pay Date", out foo))
return foo;
else
return null;
}
}
private Boolean IsLastPay() {
if (!string.IsNullOrEmpty(LastPayDate)) {
if(DateTime.Parse(Parameters.TryGetValue("Last Pay Date") >="24/05/2018")
return true;
else
return false;
}
return false;
}
however the only error I get is within below code section,
if(DateTime.Parse(Parameters.TryGetValue("Last Pay Date") > "24/05/2018")
can anyone help please ?
If you want to compare DateTimes, compare them, but not strings:
//TODO: what is the magic number (date) 24 May 2018?
private Boolean IsLastPay() {
if (Parameters.TryGetValue("Last Pay Date", out var dateSt))
if (DateTime.TryParse(dateSt, out var paramDate))
return paramDate >= new DateTime(2018, 5, 24);
else
return false; // DateTime.TryParse failed to parse the parameter
else
return false; // Parameters.TryGetValue failed to get the value
}
Thank you for respond. It did helped and I've managed to use below code and its working now, Much appreciate Help!
private Boolean IsLastPay()
{
if (!string.IsNullOrEmpty(LastPayDate))
{
string lpd;
}
if(Parameters.TryGetValue("Last Pay Date", out lpd))
{
if(DateTime.Parse(lpd) > new DateTime(2018,05,24))
return true;
else
return false;
}
}
return false;
}
Why not use the DateTime.Compare() method of DateTime class.
For this you need to have both the variables/objects of type DateTime.
string staticDate = "24/05/2018"; //dd-MM-yyyy
string inputDate = "14/08/20"; //dd-MM-yy
string greaterDate = CalculateGreaterDate(inputDate, staticDate); // 14/08/20 is greater
public static string CalculateGreaterDate(string iDate, string sDate)
{
// input date
string input = iDate;
var inputElements = input.Split('/');
int inputDay = Convert.ToInt32(inputElements[0]); //14
int inputMonth = Convert.ToInt32(inputElements[1]); //08
int inputYear = Convert.ToInt32(inputElements[2]); //20
// static date
string static = sDate;
var staticElements = static.Split('/');
int staticDay = Convert.ToInt32(staticElements[0]); //24
int staticMonth = Convert.ToInt32(staticElements[1]); //05
int staticYear = Convert.ToInt32(staticElements[2]); //2018
DateTime inputDate = new DateTime(inputYear, inputMonth, inputDay);
DateTime staticDate = new DateTime(staticYear, staticMonth, staticDay);
// DateTime.Compare(d1, d2) returns:
// > 0 : d1 is greater than d2
// = 0 : d1 & d2 are equal
// < 0 : d1 is smaller than d2
int result = DateTime.Compare(inputDate, staticDate);
if (result > 0)
return iDate + " is greater";
else if (result < 0)
return sDate + " is greater";
else if (result == 0)
return iDate + " is equal to " + sDate;
}
Related
I can't convert text ( in Maskedtextbox) to a Datetime.
For example I have these times in maskes: 16:30, 6:30
I want to show in third masked 10:00
HERE is my codes: I write a method
I have an error in line: timespan t
the error is: input string was not in a correct format
Public void A (MaskedTextBox k, MaskedTextBox k1, MaskedTextBox k2, Label k3)
{
string[] houre = k.Text.Split(':');
try
{
int h = int.Parse (houre[0].ToString();
int m = int.Parse (houre[1].ToString();
if (h > 23)
{
MessageBox.Show("wrong hour");
k.Text = "00:" + houre[1].ToString();
}
if (m > 59)
{
MessageBox.Show("wrong minute");
k.Text = houre[0].ToString() + ":00";
}
if (h > 23 && m > 59)
k.Text = "00:00";
}
catch (Exception)
{
}
string[] houre1 = k1.Text.Split(':');
try
{
int h1 = int.Parse(houre1[0].ToString());
int m1 = int.Parse(houre1[1].ToString());
if (h1 > 23)
{
MessageBox.Show("wrong hour");
k1.Text = "00:" + houre1[1].ToString();
}
if (m1 > 59)
{
MessageBox.Show("wrong minute");
k1.Text = houre1[0].ToString() + ":00";
}
if (h1 > 23 && m1 > 59)
k1.Text = "00:00";
}
catch (Exception)
{
}
TimeSpan t = TimeSpan.ParseExact(k.Text.Trim(':'), "hh:mm",null );
TimeSpan t1 = TimeSpan.ParseExact(k1.Text, "hh:mm", CultureInfo.InvariantCulture);
k2.Text = (t1 - t).ToString("hh:mm", CultureInfo.InvariantCulture);
if (k.Text != "" && k1.Text != "")
k3.Text = "IN OUT Complete";
else
k3.Text = "IN OUT Noncomplete";
You actually work with TimeSpan (not DateTime); you should Parse, do arithmetics and, finally, format the result as String:
TimeSpan left = TimeSpan.ParseExact(
maskedBox1.Text.Trim(), "h\\:m", CultureInfo.InvariantCulture);
TimeSpan right = TimeSpan.ParseExact(
maskedBox2.Text.Trim(), "h\\:m", CultureInfo.InvariantCulture);
myMaskedBox.Text = (left - right).ToString("hh\\:mm", CultureInfo.InvariantCulture);
You can try following codes:
'''
var timeString1 = "16:30";
var timeString2 = "6:30";
//Make sure the parse input string match the HH:mm format
timeString1 = timeString1.PadLeft(5, '0');
timeString2 = timeString2.PadLeft(5, '0');
var time1 = DateTime.ParseExact(timeString1, "HH:mm", null);
var time2 = DateTime.ParseExact(timeString2, "HH:mm", null);
var timeSpan12 = time1 - time2;
var result = $"{timeSpan12.Hours:d2}:{timeSpan12.Minutes:d2}";
Console.WriteLine(result);//10:30
'''
I find good way :
public static long Time(string t)
{
return
(long.Parse(t.Substring(0,2)) * TimeSpan.TicksPerHour)+
(long.Parse(t.Substring(3,2))*TimeSpan.TicksPerMinute);
}
public void Calculate(MaskedTextBox a,MaskedTextBox b,MaskedTextBox c)
{
if (Time(b.Text) > Time(a.Text))
{
long q;
q = (Time(b.Text) - Time(a.Text)) / TimeSpan.TicksPerMinute;
c.Text = TimeSpan.FromMinutes(q).ToString();
}
if (Time(b.Text) < Time(a.Text))
{
long q;
q = ((Time(b.Text)+24*TimeSpan.TicksPerHour) - Time(a.Text)) /
TimeSpan.TicksPerMinute;
c.Text = TimeSpan.FromMinutes(q).ToString();
}
if (Time(b.Text) == Time(a.Text))
c.Text = "00:00";
}
I'm currently doing my current project and I had a problem. Here's what the project needs to do:
Find the maximum and the minimum temperature from a certain range of date. The range of the date will be inputted by the user.
So, I make a form as the main menu for inputting the items and finding the maximum and minimum value (both in the new form). I also make a class to store the items:
public class TempDate
{
public double Temp { get; set; }
public DateTime Date { get; set; }
}
In the first form, just call it FormAddData, from here items will be stored into the list using a textbox and here's the code:
private void buttonSubmit_Click(object sender, EventArgs e)
{
FormMenu formMenu = (FormMenu)this.Owner;
DateTime date = dateTimePickerDate.Value.Date;
double temp = double.Parse(textBoxTemp.Text);
TempDate tempDate = new TempDate();
tempDate.Date = date;
tempDate.Temp = temp;
formMenu.listOfTempDate.Add(tempDate);
listBoxInfo.Items.Add(date + "\t" + temp + "°C");
}
In the second form that called FormMaxMinRange. In this form, I use two DateTimePicker the first one for the starting date and the second for the ending date. From here I need to make a button that will select all the items from the range that I used from starting and ending date. Here's my code:
private void buttonMaxMin_Click(object sender, EventArgs e)
{
FormMenu formMenu = (FormMenu)this.Owner;
DateTime start = dateTimePickerStart.Value.Date;
DateTime end = dateTimePickerEnd.Value.Date;
int highest = 0;
double max = formMenu.listOfTempDate[0].Temp;
int lowest = 0;
double min = formMenu.listOfTempDate[0].Temp;
for (int i = 1; i < formMenu.listOfTempDate.Count; i++)
{
if (formMenu.listOfTempDate[i].Date >= start
&& formMenu.listOfTempDate[i].Date <= end)
{
if (formMenu.listOfTempDate[i].Temp > max)
{
highest = i;
max = formMenu.listOfTempDate[i].Temp;
}
if (formMenu.listOfTempDate[i].Temp < min)
{
lowest = i;
min = formMenu.listOfTempDate[i].Temp;
}
}
}
listBoxMaxMin.Items.Add("");
listBoxMaxMin.Items.Add("Lowest temp: " + min + ", on " + formMenu.listOfTempDate[lowest].Date);
listBoxMaxMin.Items.Add("Highest temp: " + max + ", on " + formMenu.listOfTempDate[highest].Date);
}
Here's the main form that i declared the class (which include the list):
public partial class FormMenu : Form
{
public List<TempDate> listOfTempDate = new List<TempDate>();
public FormMenu()
{
InitializeComponent();
}
private void fromCertainRangeToolStripMenuItem_Click(object sender, EventArgs e)
{
FormMaxMinRange formMaxMinRange = new FormMaxMinRange();
formMaxMinRange.Owner = this;
formMaxMinRange.ShowDialog();
}
}
But, the problem is, the minimum value was not selected inside the range of selection. Also I want the max and min value was printed in the listbox. Sorry for the long and weird question. I hope someone can understand what I means with this question to complete my project. Thank you.
See this code snippet.
You can use Linq to select the reduced list (with Start/Enddate) and order it by Temp. Now you can easy select the first (min) and the last (max) object.
List<TempDate> loTempDateList = new List<TempDate>()
{
new TempDate() {Date = DateTime.Now.AddDays(-10), Temp = 10.01 },
new TempDate() {Date = DateTime.Now.AddDays(-5), Temp = 20.01 },
new TempDate() {Date = DateTime.Now.AddDays(-3), Temp = 30.01 },
new TempDate() {Date = DateTime.Now, Temp = 40.01 }
};
DateTime ldStart = DateTime.Now.AddDays(-6);
DateTime ldEnd = DateTime.Now.AddDays(-1);
var loDateList = loTempDateList.Where(item => item.Date <= ldEnd && item.Date >= ldStart)
.OrderBy(item => item.Temp);
TempDate loMin = loDateList.First();
TempDate loMax = loDateList.Last();
Console.WriteLine("{0}: {1} with max temp", loMax.Date, loMax.Temp);
Console.WriteLine("{0}: {1} with min temp", loMin.Date, loMin.Temp);
Output (for today):
9/26/2017 3:17:09 PM: 30.01 with max temp
9/24/2017 3:17:09 PM: 20.01 with min temp
Update (with your variable names):
Copy this under DateTime end = dateTimePickerEnd.Value.Date;in your Form
var loDateList = listOfTempDate.Where(item => item.Date <= end && item.Date >= start)
.OrderBy(item => item.Temp);
TempDate loMin = loDateList.FirstOrDefault();
TempDate loMax = loDateList.LastOrDefault();
if (loMin != null && loMax != null)
{
listBoxMaxMin.Items.Add("");
listBoxMaxMin.Items.Add("Lowest temp: " + loMin.Temp + ", on " + loMin.Date);
listBoxMaxMin.Items.Add("Highest temp: " + loMax.Temp + ", on " + loMax.Date);
}
I would suggest you use Linq Max and Min methods.
// filter out only the dates in the range you need
var items = formMenu.listOfTempDateWhere(
item => ((TempDate)item).Date >= start && ((TempDate)item).Date <= end
);
// get the maximum value
var max = items.Max(item => item.Temp);
// get the minimum value
var min = items.Min(item => item.Temp);
Just remember to add using System.Linq on the top of your .cs file
try this online
If you don't like a LINQ approach (I never use LINQ, for some, possibly invalid reason, I think it's evil), you can override the List class and extend it with methods of your own.
public class TempDataList<T> : List<TempData>
{
public TempDataList() : base()
{
}
public TempDataList(IEnumerable<TempData> collection) : base(collection)
{
}
public TempData GetMaxTemp(DateTime startDate, DateTime endDate)
{
TempData highestTempData = null;
for (int i = 0; i < this.Count; i++)
{
if (this[i].Date >= startDate && this[i].Date <= endDate)
{
if (highestTempData == null || this[i].Temp > highestTempData.Temp)
{
highestTempData = this[i];
}
}
}
return highestTempData;
}
public TempData GetMinTemp(DateTime startDate, DateTime endDate)
{
TempData lowestTempData = null;
for (int i = 0; i < this.Count; i++)
{
if (this[i].Date >= startDate && this[i].Date <= endDate)
{
if (lowestTempData == null || this[i].Temp < lowestTempData.Temp)
{
lowestTempData = this[i];
}
}
}
return lowestTempData;
}
}
And fill the extended list and call the methods:
TempDataList<TempData> tempDataList = new TempDataList<TempData>();
tempDataList.Add(new TempData(10, DateTime.UtcNow));
tempDataList.Add(new TempData(20, DateTime.UtcNow));
tempDataList.Add(new TempData(15, DateTime.MinValue));
tempDataList.Add(new TempData(25, DateTime.MaxValue));
Console.WriteLine(tempDataList.GetMaxTemp(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1)).Temp);
Console.WriteLine(tempDataList.GetMinTemp(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1)).Temp);
I am trying to call the GetMonths() method during the Row_Inserting() method but it shows me an error. Also, how do I copy the value of this method to a variable named Total_Pay?
public override bool Row_Inserting(OrderedDictionary rsold, ref OrderedDictionary rsnew)
{
GetMonths(FROM_DATE, TO_DATE);
return true;
}
public int GetMonths(DateTime FROM_DATE, DateTime TO_DATE)
{
if (FROM_DATE > TO_DATE)
{
throw new Exception("Start Date is greater than the End Date");
}
int months = ((TO_DATE.Year * 12) + TO_DATE.Month) - ((FROM_DATE.Year * 12) + FROM_DATE.Month);
if (TO_DATE.Day >= FROM_DATE.Day)
{
months++;
}
return months;
}
Hope this helps..
public override bool Row_Inserting(OrderedDictionary rsold, ref OrderedDictionary rsnew)
{
int Total_Pay;
DateTime FROM_DATE = DateTime.Parse("02-May-2016"); //Replace with date you need
DateTime TO_DATE = DateTime.Parse("08-May-2016"); //Replace with date you need
Total_Pay = GetMonths(FROM_DATE, TO_DATE);
return true;
}
public int GetMonths(DateTime FROM_DATE, DateTime TO_DATE)
{
if (FROM_DATE > TO_DATE)
{
throw new Exception("Start Date is greater than the End Date");
}
int months = ((TO_DATE.Year * 12) + TO_DATE.Month) - ((FROM_DATE.Year * 12) + FROM_DATE.Month);
if (TO_DATE.Day >= FROM_DATE.Day)
{
months++;
}
return months;
}
And checkout this similar question Link
just like in my questions, i have 2 calendars to be selected by users, and i would like to get the total selected days and be displayed in label.
users have to select the start date in lstartdate calendar and end date in lenddate calendar.
private void ValidateDate()
{
if (lstartdate.Text == "" || lenddate.Text == "")
{
lwarndate.Visible = true;
lwarndate.Text = "Dates required";
}
if (lstartdate.Text != "" || lenddate.Text != "")
{
if (cstart.SelectedDate > cend.SelectedDate)
{
lwarndate.Visible = true;
lwarndate.Text = "Start date must be earlier than end date!";
}
if (cstart.SelectedDate <= cend.SelectedDate)
{
lwarndate.Visible = false;
}
if (cend.SelectedDate != null && cstart.SelectedDate != null)
{
Double Value;
if (cend.SelectedDate >= cstart.SelectedDate)
Value = (cend.SelectedDate - cstart.SelectedDate).TotalDays;
else
Value = (cend.SelectedDate - cstart.SelectedDate).TotalDays;
total.Text = // ?
}
}
}
im not sure if the code arrangements are correct or not. do help and tq :)
TRY LIKE THIS
DateTime DtF = ceFromDate.SelectedDate.Value;
DateTime D1T = ceToDate.SelectedDate.Value;
double dd = (DtF - D1T).TotalDays;
total.Text = dd.ToString();
Here is simple way to get different between two dates
class Program
{
static void Main(string[] args)
{
System.DateTime dtTodayNoon = new System.DateTime(2006, 9, 13, 12, 0, 0);
System.DateTime dtTodayMidnight = new System.DateTime(2006, 9, 13, 0, 0, 0);
System.TimeSpan diffResult = dtTodayNoon.Subtract(dtYestMidnight);
Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.Days);
Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.TotalDays);
Console.ReadLine();
}
}
Source
you need to implement it yourself..
Convert the difference between the two dates into a TimeSpan, then get the amount of Days of that TimeSpan and set this as your text-value.
private void ValidateDate()
{
if (lstartdate.Text == "" || lenddate.Text == "")
{
lwarndate.Visible = true;
lwarndate.Text = "Dates required";
}
if (lstartdate.Text != "" || lenddate.Text != "")
{
if (cstart.SelectedDate > cend.SelectedDate)
{
lwarndate.Visible = true;
lwarndate.Text = "Start date must be earlier than end date!";
}else{
lwarndate.Visible = false;
}
if (cend.SelectedDate != null && cstart.SelectedDate != null)
{
TimeSpan duration = DateTime.Parse(cend.SelectedDate ).Subtract(DateTime.Parse(cstart.SelectedDate ));
total.Text = duration.Days.ToString();
}
}
}
I am developing application in Arabic/Dari/Pashto (for Afghanistan) using C# and also using Jalali/Persian calendar for date selection. I want to validate input date before saving into database. I am using below function for validation and passing Jalali/Persian calendar date to this function. It works perfectly when user select date something like "28/02/1393" but it throws error for date "31/02/1393". Both dates are valid Jalali/Persian date.
I think this issue is happenning because somehow application considering this date is English and there is no any 31st day in 2nd month in English calendar. Please help me to find solution for that.
static public bool ValidateParsianDate(string date)
{
bool status = true;
try
{
PersianCalendar persianCalendar = new PersianCalendar();
CultureInfo persianCulture = new CultureInfo("fa-IR");
DateTime persianDateTime = DateTime.ParseExact(date, "dd/MM/yyyy", persianCulture);
}
catch (Exception ex)
{
string msg = ex.Message;
status = false;
}
return status;
}
Thanks & Regards,
Rajeev
Use the PersianCalendar.ToDateTime(
int year,
int month,
int day,
int hour,
int minute,
int second,
int millisecond,
int era
) method.
static public bool ValidateParsianDate(string date)
{
bool status = true;
try
{
PersianCalendar persianCalendar = new PersianCalendar();
var dateParts = date.Split(new char[] { '/' }).Select(d=> int.Parse(d)).ToArray();
var date = persianCalendar.ToDateTime(dateParts[2], dateParts[1], dateParts[0], 0, 0,0,0, /*8 era of year here **/);
}
catch (Exception ex)
{
string msg = ex.Message;
status = false;
}
return status;
}
Because persianCulture.Calendar is set to GregorianCalendar by default in .NET framework and can't be changed to PersianCalendar without using the reflection. more info here
I had that problem but i used this and it work
public static bool IsValidDate(string date)
{
var regex = new Regex("^\\d{ 4 } /\\d{ 2}/\\d{ 2}$");
var arrPattern = new[] {
new Regex("^\\d{4}/\\d{2}/\\d{2}$"),
new Regex("^\\d{ 4 } /\\d{ 2}/\\d{ 1}$"),
new Regex("^\\d{ 4 } /\\d{ 1}/\\d{ 2}$"),
new Regex("^\\d{ 4 } /\\d{ 1}/\\d{ 1}$"),
new Regex("^\\d{ 2 } /\\d{ 2}/\\d{ 2}$"),
new Regex("^\\d{ 2 } /\\d{ 2}/\\d{ 1}$"),
new Regex("^\\d{ 2 } /\\d{ 1}/\\d{ 2}$"),
new Regex("^\\d{ 2 } /\\d{ 1}/\\d{ 1}")
};
const int kabise = 1387;
var year = 0;
var mounth = 0;
var day = 0; var flag = false;
foreach (var t in arrPattern)
{
if (t.IsMatch(date))
flag = true;
}
if (flag == false) return flag;
//جدا کننده تاریخ می تواند یکی از این کاراکترها باشد
var splitDate = date.Split('/','-',':');
year = Convert.ToInt32(splitDate[0]);
mounth = Convert.ToInt32(splitDate[1]);
day = Convert.ToInt32(splitDate[2]);
if (mounth > 12 || mounth <= 0)
flag = false;
else
{
if (mounth< 7)
{
if (day > 31)
{
flag = false;
}
}
if (mounth != 12) return flag;
var t = (year - kabise) % 4;
if ((year - kabise) % 4 == 0)
{
if (day >= 31)
flag = false;
}
else if (day >= 30)
flag = false;
}
return flag;
}