how to convert text value into 24 hour datetime object c# - c#

I have a textbox in my WPF application in which i'm getting time in 24 hour format. What I want is, if my textbox's time is less than current time then IF condition should be true but its not working...
e.g:
txtdeparturetime.Text = 00:10
time == 00:31// time==>(object) here current time
if(txtdeparturetime.Text < time) // than this should work
Below is my code.
DateTime time = new DateTime();
DateTime deptime = DateTime.Parse(txtdeparturetime.Text);//converting textbox value into date object
if ((TimeSpan.Compare(deptime.TimeOfDay, time.TimeOfDay)) == -1)
{
//some code here
}

You have some mistakes in your code...
private void button1_Click(object sender, EventArgs e)
{
DateTime t1 = DateTime.Now;
DateTime t2 = Convert.ToDateTime(textBox1.Text);
int i = DateTime.Compare(t1, t2);
if (i < 1)
{
}
}
Now, The variable i will be less than Zero if t1 is less than t2.
If t1 is equals t2 the result is Zero.
Finally, if t1 is bigger than t2 the result will be bigger than Zero.

You want to compare to DateTime.Now instead of new DateTime() and can use a simple < comparison operator.
DateTime now = DateTime.Now;
DateTime deptime = DateTime.Parse(txtdeparturetime.Text);
if (deptime.TimeOfDay < now.TimeOfDay)
{
//some code here
}
here is a working example with text set by a constant instead of a text field.
public static void test1()
{
DateTime now = DateTime.Now;
string timetext = "2017-02-04 12:16PM";
DateTime deptime = DateTime.Parse(timetext);
Console.WriteLine("text time="+timetext);
if (deptime.TimeOfDay < now.TimeOfDay)
{
Console.WriteLine("time is less than now");
}
Console.WriteLine("End");
Console.ReadLine();
}

Related

How would I calculate time left in winform?

Hi any ideas on how to calculate time left to a specific hour,
i.e. we start countdown with
if currentTime >= TimeSpan.Parse("06:40") && currentTime <= TimeSpan.Parse("07:25")
and then we parse current hour and end hour (in this example 7:25) and make a label show how many minutes and seconds are left.
I've tried making something with substracting timespan now and end time timespan but it didn't work out at all.
EDIT: The main idea is something like this, but I can't get it to work by using TimeSpan neither DateTime
string myTime;
void timer()
{
var endTime = DateTime.Parse(myTime);
var beginTime = DateTime.Now.TimeOfDay;
}
private void timer1_Tick(object sender, EventArgs e)
{
var endTime = DateTime.Parse(myTime);
var beginTime = DateTime.Now.TimeOfDay;
TimeSpan difference = endTime - beginTime;
TimeSpan currentTime = DateTime.Now.TimeOfDay;
if (currentTime >= TimeSpan.Parse("06:40") && currentTime <= TimeSpan.Parse("07:25"))
{
label5.Text = "0";
myTime = "07:25";
timer();
label6.Text = difference;
}
}
Use DateTime instead of TimeSpan when parsing points in time. TimeSpan is for durations. The difference between two points in time (DateTime) will be a duration (TimeSpan).
var end = DateTime.Parse("21:00");
var now = DateTime.Now; // Could also be some other point in time
TimeSpan timeLeft = end-now;
Console.WriteLine(timeLeft);
Result:
00:24:25.8581440
If you don't like the seconds and fractions of seconds, you can use a custom format, e.g.
Console.WriteLine(timeLeft.ToString("hh\\:mm"));

Increment previous date time

I'm trying to display date time of previous date, The date time will be incremented according to actual time, This is done to display some data on previous date time which will be incremented according actual time, Please suggest any alternate method any.The below code gets duration of base time and will increment it according to current date time.
class Program
{
private static double? Duration { get; set; }
static void Main(string[] args)
{
var startDate = DateTime.Parse("2016-11-02 11:17:55 AM");
if (!Duration.HasValue)
Duration = (DateTime.Now - startDate).TotalMinutes;
for (var count = 0; count < 10000; count++)
{
Console.WriteLine(DateTime.Now.AddMinutes(-Duration.Value).ToString("dd/MM/yyyy hh:mm:ss.fff tt"));
Thread.Sleep(100);
}
}
}
If I get your question you might need something like this:
DateTime previous = DateTime.Now;
for (var count = 0; count < 10000; count++)
{
Console.WriteLine((DateTime.Now - previous).ToString("dd/MM/yyyy hh:mm:ss.fff tt"));
previous = DateTime.Now
Thread.Sleep(100);
}
Basically you just need to store the current date now to be able to use it as previous date next time.

How to check if a date has passed in C#?

I'm reading the date expires cookie (2 hours) from database, and I need to check if this date has passed. What's the best way to do this?
For example:
public bool HasExpired(DateTime now)
{
string expires = ReadDateFromDataBase(); // output example: 21/10/2011 21:31:00
DateTime Expires = DateTime.Parse(expires);
return HasPassed2hoursFrom(now, Expires);
}
I'm looking for ideas as write the .HasPassed2hoursFrom method.
public bool HasPassed2hoursFrom(DateTime fromDate, DateTime expireDate)
{
return expireDate - fromDate > TimeSpan.FromHours(2);
}
bool HasPassed2hoursFrom(DateTime now, DateTime expires)
{
return (now - expires).TotalHours >= 2;
}
public bool HasExpired(DateTime now)
{
string expires = ReadDateFromDataBase(); // output example: 21/10/2011 21:31:00
DateTime Expires = DateTime.Parse(expires);
return now.CompareTo(Expires.Add(new TimeSpan(2, 0, 0))) > 0;
}
But since DateTime.Now is very fast and you don't need to pass it as function parameter...
public bool HasExpired()
{
string expires = ReadDateFromDataBase(); // output example: 21/10/2011 21:31:00
DateTime Expires = DateTime.Parse(expires);
return DateTime.Now.CompareTo(Expires.Add(new TimeSpan(2, 0, 0))) > 0;
}
Periodically check the date and see if now.CompareTo(expires) > 0
You can just use operators
boolean hasExpired = now >= Expires;
private enum DateComparisonResult
{
Earlier = -1,
Later = 1,
TheSame = 0
};
void comapre()
{
DateTime Date1 = new DateTime(2020,10,1);
DateTime Date2 = new DateTime(2010,10,1);
DateComparisonResult comparison;
comparison = (DateComparisonResult)Date1.CompareTo(Date2);
MessageBox.Show(comparison.ToString());
}
//Output is "later", means date1 is later than date2
To check if date has passed:
Source:https://msdn.microsoft.com/en-us/library/5ata5aya%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

How to compare HH:MM in C#

Hi I have to compare HH:MM(hour and minutes). How can i do so?
var t1 = DateTime.Now.ToString("HH:mm");
var t2 = "20:03";
var res =result(t1, t2);
public int result(string t1, string t2)
{
int i = -1;
int hr1 = Convert.ToInt32(t1.Split(':')[0]);
int hr2 = Convert.ToInt32(t2.Split(':')[0]);
int min1 = Convert.ToInt32(t1.Split(':')[1]);
int min2 = Convert.ToInt32(t2.Split(':')[1]);
if (hr2 >= hr1)
{
if (min2 >= min1)
{
i = 1;
}
}
return i;
}
But it is not correct.. it is not taking care of all conditions.. how to make it perfect. Or is there any built in function that does this with thsi input only(I checked but no answer).
Thanks in advance
If you can assume the two strings are already in the right format, just use:
return t1.CompareTo(t2);
After all, they're lexicographically sorted due to the format used - no need to parse :)
With all the references to TimeSpan... Of course if you were using Noda Time you could use:
private static readonly LocalTimePattern TimePattern =
LocalTimePattern.CreateWithInvariantInfo("HH:mm");
...
public int CompareTimes(string t1, string t2)
{
// These will throw if the values are invalid. Use TryGetValue
// or the Success property to check first...
LocalTime time1 = TimePattern.Parse(t1).Value;
LocalTime time2 = TimePattern.Parse(t2).Value;
return time1.CompareTo(time2);
}
(You can use TimeSpan if you want, of course... but LocalTime represents the actual type of data you've got: a time of day, rather than an amount of time passing ;)
Use a TimeSpan:
TimeSpan s1 = TimeSpan.Parse(t1);
TimeSpan s2 = TimeSpan.Parse(t2);
return s1.CompareTo(s2);
If you're not sure the inputs are in the correct format, you can use TryParse instead.
If these represent clock times (i.e. hour is always less than 24), then DateTime.ParseExact is what you want.
Otherwise, TimeSpan.ParseExact
If you can guarantee that the provided time is always HH:mm you can use TimeSpan.ParseExact.
You can parse the time direct from the string. Beware the culture!
var time1 = DateTime.ParseExact("12:56", "hh:mm", CultureInfo.CurrentCulture);
var time2 = DateTime.ParseExact("11:21", "hh:mm", CultureInfo.CurrentCulture);
The other solutions are more elegant and simple and deal with culture issues and should be used in professional level code.
But to fix your code, you only need to compare the minute values if and only if the hour values are equal.
var t1 = DateTime.Now.ToString("HH:mm");
var t2 = "20:03";
var res =result(t1, t2);
public int result(string t1, string t2)
{
int i = -1;
int hr1 = Convert.ToInt32(t1.Split(':')[0]);
int hr2 = Convert.ToInt32(t2.Split(':')[0]);
int min1 = Convert.ToInt32(t1.Split(':')[1]);
int min2 = Convert.ToInt32(t2.Split(':')[1]);
if (hr2 > hr1)
i = 1;
else if (hr2 = hr1 && min2 >= min1)
i = 1;
return i;
}
This works
public int CompareTime(string t1, string t2)
{
int i = -1;
int hr1 = Convert.ToInt32(t1.Split(':')[0]);
int hr2 = Convert.ToInt32(t2.Split(':')[0]);
int min1 = Convert.ToInt32(t1.Split(':')[1]);
int min2 = Convert.ToInt32(t2.Split(':')[1]);
if (hr2 == hr1)
{
if (min2 >= min1)
{
i = 1;
}
}
if (hr2 > hr1)
{
i = 1;
}
return i;
}

Ignore milliseconds when comparing two datetimes

I am comparing the LastWriteTime of two files, however it is always failing because the file I downloaded off the net always has milliseconds set at 0, and my original file has an actual value. Is there a simple way to ignore the milliseconds when comparing?
Here's my function:
//compare file's dates
public bool CompareByModifiedDate(string strOrigFile, string strDownloadedFile)
{
DateTime dtOrig = File.GetLastWriteTime(strOrigFile);
DateTime dtNew = File.GetLastWriteTime(strDownloadedFile);
if (dtOrig == dtNew)
return true;
else
return false;
}
I recommend you use an extension method:
public static DateTime TrimMilliseconds(this DateTime dt)
{
return new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, 0, dt.Kind);
}
then its just:
if (dtOrig.TrimMilliseconds() == dtNew.TrimMilliseconds())
Care should be taken, if dt has non-zero microseconds (fractions of millis). Setting only milliseconds to zero is not enough.
To set millis and below to zero (and get a succesfull comparison), the code would be:
dt = dt.AddTicks(-dt.Ticks % TimeSpan.TicksPerSecond); // TimeSpan.TicksPerSecond=10000000
Create a new DateTime value with the milliseconds component set to 0:
dt = dt.AddMilliseconds(-dt.Millisecond);
TimeSpan difference = dtNew - dtOrig;
if (difference >= TimeSpan.FromSeconds(1))
{
...
}
You can subtract them, to get a TimeSpan.
Then use TimeSpan.totalSeconds()
This is overkill for a single Truncate, but if you have several and of various types you could do this using the generalized Extension Method below:
DateTime dtSecs = DateTime.Now.TruncateTo(Extensions.DateTruncate.Second);
DateTime dtHrs = DateTime.Now.TruncateTo(Extensions.DateTruncate.Hour);
More general Use Extension method:
public static DateTime TruncateTo(this DateTime dt, DateTruncate TruncateTo)
{
if (TruncateTo == DateTruncate.Year)
return new DateTime(dt.Year, 0, 0);
else if (TruncateTo == DateTruncate.Month)
return new DateTime(dt.Year, dt.Month, 0);
else if (TruncateTo == DateTruncate.Day)
return new DateTime(dt.Year, dt.Month, dt.Day);
else if (TruncateTo == DateTruncate.Hour)
return new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, 0, 0);
else if (TruncateTo == DateTruncate.Minute)
return new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, 0);
else
return new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
}
public enum DateTruncate
{
Year,
Month,
Day,
Hour,
Minute,
Second
}
Here is the simplest way of doing this. You can control precision as you want.
bool AreEqual(DateTime a, DateTime b, TimeSpan precision)
{
return Math.Abs((a - b).TotalMilliseconds) < precision.TotalMilliseconds;
}
and usage is pretty self-explanatory
var _ = AreEqual(a, b, precision: TimeSpan.FromSeconds(1));
One way would be to create new dates, inputting the year, month, day, hour, minute, second into the constructor. Alternatively, you could simply compare each value separately.
Ether set the milliseconds in your other datetime to zero, or subtract one date from the other and just check the TotalMinutes property of the resulting time span.
instead of trimming unrelevant DateTime parts via creating new DateTimes, compare only relevant parts:
public static class Extensions
{
public static bool CompareWith(this DateTime dt1, DateTime dt2)
{
return
dt1.Second == dt2.Second && // 1 of 60 match chance
dt1.Minute == dt2.Minute && // 1 of 60 chance
dt1.Day == dt2.Day && // 1 of 28-31 chance
dt1.Hour == dt2.Hour && // 1 of 24 chance
dt1.Month == dt2.Month && // 1 of 12 chance
dt1.Year == dt2.Year; // depends on dataset
}
}
I took answer by Dean Chalk as base for performance comparison, and results are:
CompareWith is a bit faster than TrimMilliseconds in case of equal dates
CompareWith is a faster than dates are not equal
my perf test (run in Console project)
static void Main(string[] args)
{
var dtOrig = new DateTime(2018, 03, 1, 10, 10, 10);
var dtNew = dtOrig.AddMilliseconds(100);
//// perf run for not-equal dates comparison
//dtNew = dtNew.AddDays(1);
//dtNew = dtNew.AddMinutes(1);
int N = 1000000;
bool isEqual = false;
var sw = Stopwatch.StartNew();
for (int i = 0; i < N; i++)
{
// TrimMilliseconds comes from
// https://stackoverflow.com/a/7029046/1506454
// answer by Dean Chalk
isEqual = dtOrig.TrimMilliseconds() == dtNew.TrimMilliseconds();
}
var ms = sw.ElapsedMilliseconds;
Console.WriteLine("DateTime trim: " + ms + " ms");
sw = Stopwatch.StartNew();
for (int i = 0; i < N; i++)
{
isEqual = dtOrig.CompareWith(dtNew);
}
ms = sw.ElapsedMilliseconds;
Console.WriteLine("DateTime partial compare: " + ms + " ms");
Console.ReadKey();
}
You could create an extension method that would set the milliseconds to zero for a DateTime object
public static DateTime ZeroMilliseconds(this DateTime value) {
return new DateTime(value.Year, value.Month, value.Day,
value.Hours, value.Minutes, value.Seconds);
}
Then in your function
if (dtOrig.ZeroMilliseconds() == dtNew.ZeroMilliseconds())
return true;
else
return false;
Simply you can use datetime format with the format you want, and convert it again to datetime as below,
//compare file's dates
String format1 = #"yyyy-MM-dd HH:mm:ss"; // you also can avoid seconds if you want
public bool CompareByModifiedDate(string strOrigFile, string strDownloadedFile)
{
//.here we will use the format
DateTime dtOrig = Convert.ToDateTime(File.GetLastWriteTime(strOrigFile).ToString(format1));
DateTime dtNew = Convert.ToDateTime(File.GetLastWriteTime(strDownloadedFile).ToString(format1));
if (dtOrig == dtNew)
return true;
else
return false;
}
cast sortable strings and compare. simple and run well.
return string.Compare(dtOrig.ToString("s"), dtNew.ToString("s"),
StringComparison.Ordinal) == 0;
The most straightforward way to truncate time is to format it and parse on the units that you want:
var myDate = DateTime.Parse(DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss"));
DOK's method re-written
public bool CompareByModifiedDate(string strOrigFile, string strDownloadedFile)
{
DateTime dtOrig = DateTime.Parse(File.GetLastWriteTime(strOrigFile).ToString("MM/dd/yyyy hh:mm:ss"));
DateTime dtNew = DateTime.Parse(File.GetLastWriteTime(strDownloadedFile).ToString("MM/dd/yyyy hh:mm:ss"));
if (dtOrig == dtNew)
return true;
else
return false;
}
Don't know why almost all programmers needs extra lines to return a bool value from a function with a bool expression.
instead
if (dtOrig.ZeroMilliseconds() == dtNew.ZeroMilliseconds())
return true;
else
return false;
you can always just use
return dtOrig.ZeroMilliseconds() == dtNew.ZeroMilliseconds()
if the expression is true it returns true else false.

Categories

Resources