How to compare HH:MM in C# - 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;
}

Related

how to convert text value into 24 hour datetime object 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();
}

Split date range into date range chunks

I am looking for a method of splitting a date range into a series of date ranges by chunk size of days. I am planning on using this to buffer calls to a service which if the date range is too large, the service faults.
This is what I have come up with so far. It seems to work, but I am not sure if it will exit properly. This seems like something that has probably been done several times before, but I can't find it.
public IEnumerable<Tuple<DateTime, DateTime>> SplitDateRange(DateTime start, DateTime end, int dayChunkSize)
{
var newStart = start;
var newEnd = start.AddDays(dayChunkSize);
while (true)
{
yield return new Tuple<DateTime, DateTime>(newStart, newEnd);
if (newEnd == end)
yield break;
newStart = newStart.AddDays(dayChunkSize);
newEnd = (newEnd.AddDays(dayChunkSize) > end ? end : newEnd.AddDays(dayChunkSize));
}
}
I'm looking for improvement suggestions, or "Dude, use this existing function for this!"
I think your code fails when the difference between start and end is smaller than dayChunkSize.
See this:
var singleRange = SplitDateRange(DateTime.Now, DateTime.Now.AddDays(7), dayChunkSize: 15).ToList();
Debug.Assert(singleRange.Count == 1);
Proposed solution:
public static IEnumerable<Tuple<DateTime, DateTime>> SplitDateRange(DateTime start, DateTime end, int dayChunkSize)
{
DateTime chunkEnd;
while ((chunkEnd = start.AddDays(dayChunkSize)) < end)
{
yield return Tuple.Create(start, chunkEnd);
start = chunkEnd;
}
yield return Tuple.Create(start, end);
}
There are a couple of problems with your solution:
the test newEnd == end may never be true, so the while could loop forever (I now see that this condition should always be triggered, but it wasn't obvious on first reading of the code; the while(true) feels a bit dangerous still)
AddDays is called three times for each iteration (minor performance issue)
Here is an alternative:
public IEnumerable<Tuple<DateTime, DateTime>> SplitDateRange(DateTime start, DateTime end, int dayChunkSize)
{
DateTime startOfThisPeriod = start;
while (startOfThisPeriod < end)
{
DateTime endOfThisPeriod = startOfThisPeriod.AddDays(dayChunkSize);
endOfThisPeriod = endOfThisPeriod < end ? endOfThisPeriod : end;
yield return Tuple.Create(startOfThisPeriod, endOfThisPeriod);
startOfThisPeriod = endOfThisPeriod;
}
}
Note that this truncates the last period to end on end as given in the code in the question. If that's not needed, the second line of the while could be omitted, simplifying the method. Also, startOfThisPeriod isn't strictly necessary, but I felt that was clearer than reusing start.
With respect to accepted answer you could use the short form of tuples:
private static IEnumerable<(DateTime, DateTime)> GetDateRange1(DateTime startDate, DateTime endDate, int daysChunkSize)
{
DateTime markerDate;
while ((markerDate = startDate.AddDays(daysChunkSize)) < endDate)
{
yield return (startDate, markerDate);
startDate = markerDate;
}
yield return (startDate, endDate);
}
But I prefer to use named tuples:
private static IEnumerable<(DateTime StartDate, DateTime EndDate)> GetDateRange(DateTime startDate, DateTime endDate, int daysChunkSize)
{
DateTime markerDate;
while ((markerDate = startDate.AddDays(daysChunkSize)) < endDate)
{
yield return (StartDate: startDate, EndDate: markerDate);
startDate = markerDate;
}
yield return (StartDate: startDate, EndDate: endDate);
}
Your code looks fine for me. I don't really like the idea of while(true)
But other solution would be to use enumerable.Range:
public static IEnumerable<Tuple<DateTime, DateTime>> SplitDateRange(DateTime start, DateTime end, int dayChunkSize)
{
return Enumerable
.Range(0, (Convert.ToInt32((end - start).TotalDays) / dayChunkSize +1))
.Select(x => Tuple.Create(start.AddDays(dayChunkSize * (x)), start.AddDays(dayChunkSize * (x + 1)) > end
? end : start.AddDays(dayChunkSize * (x + 1))));
}
or also, this will also work:
public static IEnumerable<Tuple<DateTime, DateTime>> SplitDateRange(DateTime start, DateTime end, int dayChunkSize)
{
var dateCount = (end - start).TotalDays / 5;
for (int i = 0; i < dateCount; i++)
{
yield return Tuple.Create(start.AddDays(dayChunkSize * i)
, start.AddDays(dayChunkSize * (i + 1)) > end
? end : start.AddDays(dayChunkSize * (i + 1)));
}
}
I do not have any objects for any of the implementations. They are practically identical.
If you know how many chunks/intervals/periods/parts you want to split your time range into, I've found the following to be helpful
You can use the DateTime.Ticks property to define your intervals, and then create a series of DateTime objects based on your defined interval:
IEnumerable<DateTime> DivideTimeRangeIntoIntervals(DateTime startTS, DateTime endTS, int numberOfIntervals)
{
long startTSInTicks = startTS.Ticks;
long endTsInTicks = endTS.Ticks;
long tickSpan = endTS.Ticks - startTS.Ticks;
long tickInterval = tickSpan / numberOfIntervals;
List<DateTime> listOfDates = new List<DateTime>();
for (long i = startTSInTicks; i <= endTsInTicks; i += tickInterval)
{
listOfDates.Add(new DateTime(i));
}
return listOfDates;
}
You can convert that listOfDates into however you want to represent a timerange (a tuple, a dedicated date range object, etc). You can also modify this function to directly return it in the form you need it.
There are a lot of corner cases that are unhandled in the answers so far. And it's not entirely clear how you would want to handle them. Do you want overlapping start/end of ranges? Is there a minimum range size? Below is some code that'll handle some of the corner cases, you'll have to think about overlapping especially and possibly push the start/end of ranges by a few seconds or maybe more depending on the data you're returning.
public static IEnumerable<(DateTime start, DateTime end)> PartitionDateRange(DateTime start,
DateTime end,
int chunkSizeInDays)
{
if (start > end)
yield break;
if (end - start < TimeSpan.FromDays(chunkSizeInDays))
{
yield return (start, end);
yield break;
}
DateTime e = start.AddDays(chunkSizeInDays);
for (;e < end; e = e.AddDays(chunkSizeInDays))
{
yield return (e.AddDays(-chunkSizeInDays), e);
}
if (e < end && end - e > TimeSpan.FromMinutes(1))
yield return (e, end);
}
Example call:
static void Main(string[] _)
{
Console.WriteLine("expected");
DateTime start = DateTime.Now - TimeSpan.FromDays(10);
DateTime end = DateTime.Now;
foreach (var range in PartitionDateRange(start, end, 2))
{
Console.WriteLine($"{range.start} to {range.end}");
}
Console.WriteLine("start > end");
start = end + TimeSpan.FromDays(1);
foreach (var range in PartitionDateRange(start, end, 2))
{
Console.WriteLine($"{range.start} to {range.end}");
}
Console.WriteLine("less than partition size");
start = end - TimeSpan.FromDays(1);
foreach (var range in PartitionDateRange(start, end, 2))
{
Console.WriteLine($"{range.start} to {range.end}");
}
}
The accepted solution looks good in most cases. If you need to take away overlap on the beginning and the end of each chunk, then this might work better.
public static IEnumerable<(DateTime FromDate, DateTime ToDate)> SplitDateRange(DateTime start, DateTime end, int dayChunkSize)
{
DateTime chunkEnd;
while ((chunkEnd = start.AddDays(dayChunkSize-1)) < end)
{
yield return (start, chunkEnd);
start = chunkEnd.AddDays(1);
}
yield return (start, end);
}
hare is an example spliced by month
IEnumerable<(DateTime, DateTime)> SplitDateRange(DateTime start, DateTime end, int monthChunkSize)
{
DateTime dateEnd=DateTime.Parse(end.ToString());
for (int i = 0;start.AddMonths(i) < dateEnd; i+=monthChunkSize)
{
end = start.AddMonths(i+monthChunkSize);
start.AddMonths(i);
yield return (start.AddMonths(i), end<dateEnd?end:dateEnd);
}
}

Not sure what type it should be

I want to extract all the sundays in the current month and have this code:
private string GetDatesOfSundays(DateTime DatMonth)
{
string sReturn = "";
int iDayOffset = DatMonth.Day - 1;
DatMonth = DatMonth.AddDays(System.Convert.ToDouble(-DatMonth.Day + 1));
DateTime DatMonth2 = DatMonth.AddMonths(1).AddDays(System.Convert.ToDouble(-1));
while (DatMonth < DatMonth2)
{
if (DatMonth.DayOfWeek == System.DayOfWeek.Sunday)
{
if (sReturn.Length > 0) sReturn += ",";
sReturn += DatMonth.ToShortDateString();
}
DatMonth = DatMonth.AddDays(1.0);
}
return sReturn;
}
[HttpGet]
public ActionResult TradeUKKPISearchesData()
{
string allSundaysInMonth = GetDatesOfSundays(System.DateTime.Now);
//var reportData = _reportingService.GetTradeUKKPISearches();
//return View(reportData);
}
the problem lies with my type string for allSundaysInMonth and is also empty ofcourse. The sReturn is of type string but then again I pass a date(I know :) ) but what type should allSundaysInMonth be? sReturn does have the correct dates in...I need to display these dates in a dropdown in the view of the controller so the user can select any of the sundays for which he/she needs to run a report for.
thanks
How about
private IEnumerable<DateTime> GetDatesOfSundays(DateTime DatMonth)
{
int iDayOffset = DatMonth.Day - 1;
DatMonth = DatMonth.AddDays(System.Convert.ToDouble(-DatMonth.Day + 1));
DateTime DatMonth2 =
DatMonth.AddMonths(1).AddDays(System.Convert.ToDouble(-1));
while (DatMonth < DatMonth2)
{
if (DatMonth.DayOfWeek == System.DayOfWeek.Sunday)
{
yield return DatMonth;
}
DatMonth = DatMonth.AddDays(1.0);
}
}
I would be tempted to rewrite your function as an extension somthing like this
public static IEnumerable<Datetime> DaysOfMonth(
this DateTime any,
DayOfWeek day)
{
// start at first of month
var candidate = new DateTime(any.Year, any.Month, 1);
var offset = (int)day - (int)candidate.DayOfWeek;
if (offset < 0)
{
offset += 7
}
candidate = candidate.AddDays(offset);
while (cadidate.Month == any.Month)
{
yield return candidate;
candidate = candidate.AddDays(7.0)
}
}
Then you could use it like this
var allSundaysInMonth = DateTime.Now.DaysOfMonth(DayOfWeek.Sunday);
If you want to convert an IEnumerable<DateTime> to a string you could do this,
var listOfDates = string.Join<DateTime>(", ", allSundaysInMonth);
using this string.Join overload
If you really want the days as a DateTime[] you could do this (but there is no need)
DateTime[] allSundaysInMonth = GetDatesOfSundays(DateTime.Now).ToArray();
or for my extension example
var allSundaysInMonth = DateTime.Now.DaysOfMonth(DayOfWeek.Sunday).ToArray();
You can go for DateTime[] or IEnumerable<DateTime>.
Your method signature should be
private IEnumerable<DateTime> GetDatesOfSundays(DateTime DatMonth)
or
private DateTime[] GetDatesOfSundays(DateTime DatMonth)
If you havn't worked with IEnumerable go for this
private DateTime[] GetDatesOfSundays(DateTime DatMonth)
{
List<DateTime> lst = new List<DateTime>();
DatMonth = DatMonth.AddDays(-DatMonth.Day + 1);
DateTime DatMonth2 = DatMonth.AddMonths(1).AddDays(System.Convert.ToDouble(-1));
while (DatMonth < DatMonth2)
{
if (DatMonth.DayOfWeek == System.DayOfWeek.Sunday)
{
lst.Add(DatMonth);
DatMonth = DatMonth.AddDays(7);
continue;
}
DatMonth = DatMonth.AddDays(1);
}
return lst.ToArray();
}
and call it as
DateTime[] allSundaysInMonth = GetDatesOfSundays(System.DateTime.Now);

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

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