is this possible to assign a value to TimeSpan? - c#

I have to thank for the early help to advise the "Tick". Now am pretty much got in to my logic except one thing, i have a unix time in my database ,when i was trying to convert to real time and do the logic.
Sorry, let me describe the problem once again,
I have four different timestamp pulled out from DB (Start,End,Start1,End1) converted from unix to real time. am using the following code to do the conversion
DateTime = Convert.ToDateTime("1/1/1970").AddSeconds(SnapTo5Mins(Convert.ToDouble(UnixDate))).AddHours(GMTOFFset);
Problem here is,when the value is zero in the coloumn then the date time is returning like (1/1/1970).
for eg. my start value is zero in the database then it retruns (1/1/1970)
Step 1: compare the timestamp is not equal to 1/1/1970 (origin time)
step 2: if its not equal then do Break = End.Subtract(Start); Step
3: if its equal then assign the break value to zero or whatever step
4: repeat step 1,2,3 for start1 step 5: concatenate both break +
break1
DateTime Origin = new DateTime(1970, 1, 1, 12, 0, 0, 0);
DateTime Start ="01/01/1970 12:00";
DateTime End = 01/01/1970 12:00";
DateTime Start1 ="02/10/2013 12:20";
DateTime End1 = "02/10/2013 02:20";
TimeSpan Break;,finalMealBreak1;
if (Origin.Year != Start.Year)
{
Break = End.Subtract(Start);
}
else
{
Break = //Assign constant value zero
}
if (Origin.Year != Start1.Year)
{
Break1 = End1.Subtract(Start1);//break1 value must be 2hrs
}
else
{
Break1 = //Assign constant value zero
}
TimeSpan FinalBreakResult = Break + Break1; (FinalBreakresult value suppose to be 2 hrs )
Thanks in advance

Not 100% sure what you are trying to get from the timespan, I think 0? But you can do a few things to get values.
TimeSpan.Zero // timespan of 0
DateTime.Now.TimeOfDay // returns a value of the current time in a timespan
// obviously also works with any datetime
TimeSpan.FromSeconds(100) // timespan with 100 seconds
// There are a few of these, like FromHours, FromDays
Edit: Using your code
DateTime Origin = new DateTime(1970, 1, 1, 12, 0, 0, 0);
DateTime Start = DateTime.Parse("01/01/1970 12:00:00");
DateTime End = DateTime.Parse("01/01/1970 12:00:00");
DateTime Start1 = DateTime.Parse("02/10/2013 12:20:00");
DateTime End1 = DateTime.Parse("02/10/2013 14:20:00");
TimeSpan Break, Break1;
if (Origin.Year != Start.Year)
{
Break = End.Subtract(Start);
}
else
{
Break = TimeSpan.Zero;
}
if (Origin.Year != Start1.Year)
{
Break1 = End1.Subtract(Start1);//break1 value must be 2hrs
}
else
{
Break1 = TimeSpan.Zero;
}
TimeSpan FinalBreakResult = Break + Break1;
// Value of FinalBreakResult is 2 hours

Of course. To add to #Dan Saltmer's answer:
DateTime then = DateTime.Now;
Thread.Sleep(500);
TimeSpan span = DateTime.Now - then;

Related

DateTime or TimeSpan Data mask?

I am looking for a completely customized DateTime property data mask for the TimeSpan part of the DateTime. Or if it makes things easier I can make the property itself a TimeSpan
I need to display in 24 hour time without the seconds like these examples: 8:45 , 17:36
I need the input data to be like these examples: 845 == 8:45, 1736 == 17:36
Ie, the user does not have to enter the semicolon :
I know you can format time into a string like this,
string time = new TimeSpan(8, 45, 0).ToString("HH:mm")
But it can't be a string.
I have looked at the Docs and I can't put the this together myself. If someone could point me in the right direction as to what the mask needs to be that would be great.
EDIT: It is in WinForms
Cheers
As others mentioned, you'll need to create some conversion methods yourself. This code might help.
// Display current time
Console.WriteLine(DateTime.Now.ToString("HHmm").TrimStart('0'));
// Read some input
var str = Console.ReadLine();
// Validate input (if required)
int time;
if (!int.TryParse(str, out time) || time < 100 || time > 2359)
{
Console.WriteLine("Invalid time");
return;
}
int h = time / 100;
int m = time % 100;
if (m > 59)
{
Console.WriteLine("Invalid time");
return;
}
// Construct TimeSpan and DateTime
var timeSpan = new TimeSpan(h, m, 0); // You have the TimeSpan here
var dateTime = DateTime.Now.Date + timeSpan; // You have the DateTime here
Console.WriteLine(timeSpan);
Console.WriteLine(dateTime);

Change the time forward

I am getting dates from the database and for each date I want to change the time forward starting from the DateTime that was obtained from the database until I get to a given Fixed Time (Y). However, (Y) might be in the next day.
For example if the date from the database is [7/6/2017 5:00:00 AM] and the given Fixed Time is 10:00 PM then I want to get [7/6/2017 10:00:00 PM].
However if the fixed time is 02:00 AM then I want to get [7/7/2017 02:00:00 AM] (notice that the date has increased by one)
Note: The code is running, but I modified the code to make it shorter and make more sense. Thus, there might be syntax or spelling mistakes.
My first solution was something like this:
private DateTime setTimeForeward(DateTime date) {
DateTime today = DateTime.ParseExact(FixedTime, "hh:mm tt", CultureInfo.InvariantCulture);
TimeSpan difference = today.TimeOfDay - date.TimeOfDay;
return date + difference;
}
That didn't work as expected when the fixed time is 02:00 AM. The difference becomes negative( it doesn't go around the clock) and the date will be [7/6/2017 02:00:00 AM].
I ended up with the following code
private DateTime setTimeForeward(DateTime date) {
DateTime today = DateTime.ParseExact(FixedTime "hh:mm tt", CultureInfo.InvariantCulture);
TimeSpan difference = today.TimeOfDay - date.TimeOfDay;
if (difference.Hours < 0) {
difference += new TimeSpan(24, 0, 0);
}
return date + difference;
}
I am not sure if my function is logically correct and I feel like I am overthinking it. Also,I am not sure if there's a better way or a built in function that does what I want for me. Basically, I am looking for a correct and an elegant solution.
Thank you very much in advanced.
In this method, I'm using DateTime fixedTime to represent a time. I don't really care about it's Day, Month, and Year values.
static DateTime GetClosingTime(DateTime fixedTime, DateTime dbTime)
{
var cutoff = new DateTime(dbTime.Year, dbTime.Month, dbTime.Day, fixedTime.Hour, fixedTime.Minute, fixedTime.Second);
if (dbTime < cutoff)
return cutoff;
else
{
cutoff = cutoff.AddDays(1);
return cutoff;
}
}
Here's calling it with your provided example input.
var FixedTime10PM = new DateTime(1, 1, 1, 22, 0, 0);
var FixedTime02AM = new DateTime(1, 1, 1, 2, 0, 0);
var dbTime = new DateTime(2018, 6, 20, 5, 0, 0);
var dt1 = GetClosingTime(FixedTime10PM, dbTime);
var dt2 = GetClosingTime(FixedTime02AM, dbTime);
Console.WriteLine(dt1.ToLongDateString() + " " + dt1.ToLongTimeString());
Console.WriteLine(dt2.ToLongDateString() + " " + dt2.ToLongTimeString());
And here's my output:
EDIT:
Simplified method based on suggestions in comments:
static DateTime GetClosingTime(DateTime fixedTime, DateTime dbTime)
{
var cutoff = new DateTime(dbTime.Year, dbTime.Month, dbTime.Day, fixedTime.Hour, fixedTime.Minute, fixedTime.Second);
return dbTime < cutoff ? cutoff : cutoff.AddDays(1);
}
Your logic is almost right but you shouldn't be checking for difference.Hours because there might be a difference in minutes (or even seconds if you changed the format later).
I adjusted your function and changed some variable names to make them easier to follow:
private DateTime SetTimeForward(DateTime originalDate)
{
TimeSpan newTime = DateTime.ParseExact(FixedTime,
"hh:mm tt",
CultureInfo.InvariantCulture).TimeOfDay;
TimeSpan diff = newTime - originalDate.TimeOfDay;
if (diff.Ticks < 0)
diff = diff.Add(new TimeSpan(24, 0, 0));
return originalDate.Add(diff);
}
Some remarks:
If your FixedTime is really fixed, you might want to store it directly as a TimeSpan so you don't have to parse it every time.
If you parse the FixedTime because it's changeable, you might pass it as a second argument instead:
private DateTime SetTimeForward(DateTime originalDate, string fixedTime)
Or:
private DateTime SetTimeForward(DateTime originalDate, TimeSpan newTime)
The current implementation does not change the date value if the newTime is equal to originalDate.TimeOfDay. I.E., If the originalDate is 7/6/2017 2:00 AM and the FixedTime/newTime is 02:00 AM, the returned date will be equal to the originalDate. If that's not your desired behavior, you might change diff.Ticks < 0 to diff.Ticks <= 0.
Slightly different approach:
private DateTime setTimeForeward(DateTime date)
{
var targetTimeOfDay = TimeSpan.ParseExact(FixedTime, "hh:mm tt", CultureInfo.InvariantCulture);
if (targetTimeOfDay < date.TimeOfDay)
{
date = date.AddDays(1);
}
return date.Date + targetTimeOfDay;
}
I'm getting target time as TimeSpan from the beginning instead of creating DateTime and getting TimeOfDay (which is TimeSpan).
Then I check if the target time of day is lower than time to be modified and if it is I add one day.
I use date.Date + targetTimeOfDay as return value as date.Date will return date with time set to 00:00 and adding target time to it will already set the target hour without calculating the difference.

How to check if DateTime is within a specific range

I'm developing a video rental application using C# winforms, and came across a problem I can't seem to write up or find the solution to.
The program needs to check the current date and number of days passed and also the range between them.
If the current Date is less than or equal to the date specified, it will not calculate the penalty cost.
Otherwise if the Date today has already passed the date specified, it will calculate the penalty cost multiplied by the number of days that has passed between them.
Here's the sample code I have playing with the idea:
DateTime db = DateTime.Parse(dateBeforeString);
DateTime dt = DateTime.Now;
var dateDiff = (dt - db);
double totalDays = dateDiff.TotalDays;
int totalPenalty = initialPenaltyInt*(int)Convert.ToInt64(totalDays);
int totalCost = totalPenalty + rentalCostInt;
if(DateTime.Now != db)
{
//do stuff here to:
//check if current day is less than the one on the database
//set total penalty to zero
}
else if(DateTime.Now > db)
{
//otherwise calculate the total penalty cost multipled by the number of days passed since a specific date
}
Simplistic, but might help you progress, hopefully:
public class Penalties
{
// What about this choice of "int" (vs. decimal)?
public virtual int ComputeOverdueDaysPenalty(int penaltyPerOverdueDay, DateTime dueDate)
{
// Work only with year, month, day, to drop time info and ignore time zone
dueDate = new DateTime(dueDate.Year, dueDate.Month, dueDate.Day);
var now = DateTime.Now;
now = new DateTime(now.Year, now.Month, now.Day);
return now > dueDate ? (int)now.Subtract(dueDate).TotalDays * penaltyPerOverdueDay : 0;
}
}
class Program
{
static void Main(string[] args)
{
var penalties = new Penalties();
var now = DateTime.Now;
// due = today
// should print 0
Console.WriteLine(penalties.ComputeOverdueDaysPenalty(1234, new DateTime(now.Year, now.Month, now.Day)));
// due = today plus 1
var dueDate = now.AddDays(1);
// should print 0 again
Console.WriteLine(penalties.ComputeOverdueDaysPenalty(1234, dueDate));
// due = today minus 1
dueDate = dueDate.Subtract(new TimeSpan(48, 0, 0));
// should print 1234
Console.WriteLine(penalties.ComputeOverdueDaysPenalty(1234, dueDate));
// due = today minus 2
dueDate = dueDate.Subtract(new TimeSpan(24, 0, 0));
// should print 2468
Console.WriteLine(penalties.ComputeOverdueDaysPenalty(1234, dueDate));
dueDate = DateTime.Parse("2016-10-02");
// should print 12340, as of 10/12/2016
Console.WriteLine(penalties.ComputeOverdueDaysPenalty(1234, dueDate));
Console.ReadKey();
}
}
Just a remark:
I find it a bit odd you've settled for using the int type in that context, btw.
If your "penalty" units are in fact some currency, the recommended data type for that is decimal, in most use cases.
'Hope this helps.

Determine if a date is a "work day off"

At my work, we are on the 9/80 plan where we get every other Friday off. We've got a small program that shows a DevExpress.Scheduler control and I'd like to color our "Friday's off" a different color. What I need to know is how do I know if a date is one of our Friday's off? The Friday's off will always be every other week (in other words, we don't skip a week due to a holiday or something like that). I have the date of our First Friday off of the year, so I think I can use that somehow...I can also get the date from the scheduler as it's drawn so I have something to compare to.
DateTime dtFirstFridayOff = new DateTime(2011, 1, 1);
DateTime dtCellDate = Convert.ToDateTime(e.Cell.Value);
Now I'm a bit lost as to how to check if dtCellDate is a Friday off.
public static bool IsDateMultipleDays(DateTime originalDate, int numberOfDays, DateTime potentialDate)
{
var original = originalDate.Date; // to make sure that it doesn't have a time portion
var potential = potentialDate.Date;
var difference = potential - original;
return (int)difference.TotalDays % numberOfDays == 0;
}
Then you'd call it like this:
IsDateMultipleDays(dtFirstFridayOff, 14, dtCellDate)
Try this:
bool IsFridayOff(DateTime dt)
{
if (dt.DayOfWeek != DayOfWeek.Friday)
{
return false;
}
DateTime dtFirstFridayOff = new DateTime(2011, 1, 1);
TimeSpan span = dtFirstFridayOff - dt.Date;
return (int) span.TotalDays%14 == 0;
}

Date comparison - How to check if 20 minutes have passed?

How to check if 20 minutes have passed from current date?
For example:
var start = DateTime.Now;
var oldDate = "08/10/2011 23:50:31";
if(start ??) {
//20 minutes were passed from start
}
what's the best way to do this?
Thanks :)
You should convert your start time to a UTC time, say 'start'.
You can now compare your start time to the current UTC time using:
DateTime.UtcNow > start.AddMinutes(20)
This approach means that you will get the correct answer around daylight savings time changes.
By adding time to the start time instead of subtracting and comparing the total time on a TimeSpan you have a more readable syntax AND you can handle more date difference cases, e.g. 1 month from the start, 2 weeks from the start, ...
var start = DateTime.Now;
var oldDate = DateTime.Parse("08/10/2011 23:50:31");
if ((start - oldDate).TotalMinutes >= 20)
{
//20 minutes were passed from start
}
var start = DateTime.Now;
var oldDate = DateTime.Parse("08/10/2011 23:50:31");
if(start.Subtract(oldDate) >= TimeSpan.FromMinutes(20))
{
//20 minutes were passed from start
}
Parse oldDate into a DateTime object (DateTime.Parse).
Subtract the parsed date from start. This will return a TimeSpan.
Inspect TotalMinutes.
I was able to accomplish this by using a JodaTime Library in my project. I came out with this code.
String datetime1 = "2012/08/24 05:22:34";
String datetime2 = "2012/08/24 05:23:28";
DateTimeFormatter format = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss");
DateTime time1 = format.parseDateTime(datetime1);
DateTime time2 = format.parseDateTime(datetime2);
Minutes Interval = Minutes.minutesBetween(time1, time2);
Minutes minInterval = Minutes.minutes(20);
if(Interval.isGreaterThan(minInterval)){
return true;
}
else{
return false;
}
This will check if the Time Interval between datetime1 and datetime2 is GreaterThan 20 Minutes. Change the property to Seconds. It will be easier for you know. This will return false.
var end = DateTime.Parse(oldDate);
if (start.Hour == end.Hour && start.AddMinutes(20).Minute >= end.Minute)

Categories

Resources