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);
Related
I need to make a calculation of passed and remaining time of an operation in C#.
I have the start of the operation saved in a string format of HH:MM:SS
I have a default time length of the operation in a string format of HH:MM:SS
Now I would like to calculate:
The remaining time / extra time: For example if the operation is still below the default length, it should display -HH:MM:SS, and if the operation took longer than the default time, it should display +HH:MM:SS
If the operation took longer, I would also like to have a double value of HH,MM in % style. For example: 3hours and 30 minutes should be displayed as 3,5
Both results to be displayed next to each other.
I know I have to translate the string values into DateTime and/or TimeSpan values to do calculations, but currently I have no idea how to calculate since the first operation for example would not give me a negative value, but just get back in time [22:30:00 of yesterday].
Try this..
var start = "17:05:11"; // Pass this as a parameter
var startTime = DateTime.Parse(start);
var defaultDuration = TimeSpan.FromMinutes(2);
TimeSpan operationDuration = startTime - DateTime.Now;
TimeSpan diff = defaultDuration - operationDuration;
if (operationDuration > defaultDuration)
{
Console.Out.WriteLine($"+{diff.Hours}:{diff.Minutes}:{diff.Seconds}");
}
else
{
Console.Out.WriteLine($"-{diff.Hours}:{diff.Minutes}:{diff.Seconds}");
Console.Out.WriteLine($"{diff.Hours},{Math.Round(((double)(diff.Minutes * 100 / 60)),0, MidpointRounding.AwayFromZero)}");//example: 3hours and 30 minutes should be displayed as 3,5
}
At first save the default time as TimeSpan. Then you can take DateTime.Now and save it when the operation starts. Take another DateTime.Now later when it finished. After this point you can calculate the TimeSpan for the current operation. Then you can calculate the difference from these two TimeSpans as another TimeSpan. It can be positive or negativ and with these values you can do whatever you want.
TimeSpan defaultDuration = new TimeSpan(3, 30, 0);
DateTime begin = DateTime.Now;
//Do some work
DateTime end = DateTime.Now;
TimeSpan thisDuration = end - begin;
Console.WriteLine("Default: " + defaultDuration.ToString("hh\\:mm\\:ss"));
Console.WriteLine("This time: " + thisDuration.ToString("hh\\:mm\\:ss"));
Console.Write("Difference: ");
if (thisDuration > defaultDuration)
Console.Write("-");
Console.WriteLine((thisDuration - defaultDuration).ToString("hh\\:mm\\:ss"));
I am trying to create script that checks is the current time passed, but getting some errors.
DateTime currentTime = DateTime.Now;
TimeSpan pauseMin = TimeSpan.FromMinutes(1);
TimeSpan compare = currentTime + pauseMin;
if (currentTime >= compare)
return null;
I would write this as
DateTime currentTime = DateTime.Now;
TimeSpan pauseMin = TimeSpan.FromMinutes(1);
DateTime compare = currentTime.Add(pauseMin);
if (currentTime >= compare) {
return null;
}
This uses the type of object that you are trying to represent with everything. DateTime's can have Timespan's added to them: https://msdn.microsoft.com/en-us/library/system.datetime.add%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
Or Istern's answer if you are always just adding an integer of minutes to the time.
You can't compare DateTime and TimeSpan.
Try
var compare = currentTime.AddMinutes(1)
If you need to somehow use TimeSpan, use Jamie F's answer.
DateTime and TimeSpan is different. You can use currentTime like this:
TimeSpan currentTime = TimeSpan.FromTicks(DateTime.Now.Ticks);
And you can get passed minutes like this:
double minutes = (compare - currentTime).TotalMinutes;
If you just want to pause for 1 minute, you can use
System.Threading.Thread.Sleep(1000 * 60); // 1 minute = 60000 milliseconds
If you want your function to run for 1 minute, you can use something like
var returnAt = DateTime.Now().AddMinutes(1);
while ( true )
{
// your code here ?
if ( DateTime.Now() >= returnAt ) return null;
}
i am new to c# and i have been trying to create a code that shows the total number of hours worked..eg a person working from 8am to 4pm means he works 8 hrs a day.
i want a code that shows how many hours he worked.
i tried for loop but i am not getting it right..
please help me out
int from = Convert.ToInt32(frA.Text);
int to = Convert.ToInt32(toA.Text);
for (from = 0; from <= to; from++)
{
totalA.Text = from.ToString();
}
A loop isn't what you need here. You could use DateTime and a Timespan:
DateTime start = new DateTime(2013, 07, 04, 08,00, 00);
DateTime end = new DateTime(2013, 07, 04, 16,00, 00);
TimeSpan ts = end - start;
Console.Write(ts.Hours);
Here I create two DateTime objects for today (04/07/2013). One has the start time of 08:00 and the end time 16:00 (4pm).
The Timespan object ts subtracts these dates, you can then use the .Hours property.
You first have to convert the string to int, then you can initialize a TimeSpan struct:
int from, to;
if (int.TryParse(frA.Text, out from) && int.TryParse(toA.Text, out to))
{
if (to <= from)
MessageBox.Show("To must be greater than From.");
else
{
TimeSpan workingHours = TimeSpan.FromHours(to - from);
// now you have the timespan
int hours = workingHours.Hours;
double minutes = workingHours.TotalMinutes;
// ...
}
}
else
MessageBox.Show("Please enter valid hours.");
You don't really need the TimeSpan here, you could also use the int alone. Used it anyway to show that it allows to provide other properties like minutes or second.
If that inputs can be taken to DateTime, then you can do it like the following line of code
double totalHours = (DateTime.Now - DateTime.Now).TotalHours;
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;
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)