It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm adding time span with interval size(suppose one minute) in a loop and whenever it gets 23:59 and at this point I'm trying to add one minute, it giving me result 1.00:00:00:00 something like this. How can i get continuous adding intervals when it comes 23:59:00 like
00:00:00
00:01:00
00:02:00
Thanks.
Either
When displaying your timespan, ignore the days part:
string toDisplay = yourTimeSpan.ToString("hh:mm:ss");
After incrementing your timespan, subtract a day if it is a day or longer:
if (yourTimeSpan.Days == 1)
yourTimeSpan = yourTimeSpan.Subtract(TimeSpan.FromDays(1));
// or Wonko the Sane's improved version
if (yourTimeSpan.Days > 0) yourTimeSpan = new TimeSpan();
Whenever your TimeSpan gets over one day, it will format itself in ToString() adding that day to returned string. You could either format ToString() or substract one day after you accumulate it. If you would like your TimeSpan not to go over one day, check this code:
TimeSpan ts = new TimeSpan();
DateTime dt = new DateTime();
TimeSpan day = dt.AddDays(1) - dt;
TimeSpan minute = dt.AddMinutes(1) - dt;
for (int i = 0; i < 20000; i++)
{
ts = ts.Add(minute);
if (ts.TotalDays > 1)
{
ts = ts.Subtract(day);
}
}
I assume you're printing out the value of your TimeSpan just using the standard toString() method? this will yield the TimeSpan in a "human formatted" time representation, e.g. 25 hours will be 1 day and 1 hour.
If you want to get the total number of minutes, for example use the TimeSpan.TotalMinutes proprety
You want it to loop back to 00:00 after reaching 23:59?
In your loop, or wherever you're trying to achieve this, check if the Days component is bigger than 0, and if so, subtract one day.
Seems too simple an aswer to be right... what do you really look for?
After your TimeSpan reaches more than a day, you'll get that form of output. If you still want to show it in hour form, try something like
String.format({0}:{1}:{2}, span.Days*24 + span.Hours, span.Minutes, span.Seconds)
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
How do i go about creating a datetime based on only the following information:
Day of Week, Hour & Minuet.
I.e. I don't care what month it is or even what the date is (i don't have that info in the database).
I thought i could parse them as a string but is turning out to be more difficult than i thought.
Created on function for you it might be helpful to you ..
public DateTime CreateDayOfWeek(int DayOfWeek,int hour,int min)
{
DateTime dt = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,hour,min,0);
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysUntilTuesday = (DayOfWeek - (int)dt.DayOfWeek + 7) % 7;
// DateTime nextTuesday = today.AddDays(daysUntilTuesday);
dt = dt.AddDays(daysUntilTuesday);
return dt;
}
I have tested for several dates and its working for me ..
let me know if you have any issue ..
Here is .netFiddle
You can create your date like this...
var hour = 1; // you set this from code
var minute = 1; // set this from code
var now = DateTime.Now;
var tempDateTime = new DateTime(now.Year, now.Month, now.Day, hour, minute, 0);
// Make this enum whatever you want your date to be...
var num = (int)DayOfWeek.Sunday;
var dateForComparison = tempDateTime.AddDays(num - (int)tempDateTime.DayOfWeek);
Now dateForComparison holds a date that has your time values set and the day of week you have specified.
You said you don't care about what month or date it is, which makes me assume you want any date as long as it is the right day of week and time (hour and minute). You can do it like this:
var date = new System.DateTime(2016, 9, 25);
date = date.AddDays(dow).AddHours(hours).AddMinutes(minutes);
September 25, 2016 was a Sunday. Add the day of the week (Sunday = 0) and you get the correct day. Then add the hours and minutes. Of course, if you like you can pick any Sunday of any month/year to start.
You can create a function for build your date:
public DateTime BuildDate(Int32 day, Int32 hour, Int32 minute)
{
var now = DateTime.Now;
var initialDate = now.AddDays(((Int32)now.DayOfWeek + 1) * -1);
return new DateTime(initialDate.Year, initialDate.Month, initialDate.AddDays(day).Day, hour, minute, 0);
}
The day of week is start from sunday in this case.
You can use: DateTime.ToString Method (String)
DateTime.Now.ToString("ddd HH:mm") // for military time (24 hour clock)
More: https://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I want to compare to dates like :
I have an Variable DateTime, and I want compare if the TIME of this variable is smaller than actual TIME ...
ex:
Datetime DateT = new DateTime.Now;
string Myvariable = "13:00:36";
You can use DateTime.TryParseExact Method and DateTime.TimeOfDay Property as below
string value = "13:00:36";
DateTime dt;
if (DateTime.TryParseExact(value, "HH:mm:ss", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
if (dt.TimeOfDay > DateTime.Now.TimeOfDay)
{
// greater than actual time
}
else
{
// smaller than actual time
}
}
Since you have time in string format it is difficult to compare. What you can do is convert it to Datetime by giving correct format string. Now you have two DateTime objects and you can get Time of those object by TimeOfDay property and compare..
Have you tried to use the DateTime variable instead? Something like this:
DateTime date1 = new DateTime(2013, 1, 1, 13, 00, 36);
DateTime dateNow = new DateTime.Now;
Console.WriteLine(date1.ToString("T", CultureInfo.CreateSpecificCulture("es-ES")));
// Outputs 6:30:00
Console.WriteLine(date1.ToString("U", CultureInfo.CreateSpecificCulture("en-US")));
// Outputs Tuesday, January 1, 2013 13:00:36 PM
Console.WriteLine(dateNow.ToString());
// Outputs the current date/time
Then you can create another DateTime and compare them as DateTime variable, not strings, although you can still output the values as strings using date1.ToString() function.
More info about it here: http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
Hope it helps.
Use the following code to get the time string as a DateTime instance:
DateTime DateT = new DateTime.Now;
string Myvariable = "13:00:36";
DateTime parsedTime = DateTime.ParseExact(
Myvariable,
"HH:mm:ss",
CultureInfo.InvariantCulture);
The parsedTime will have the time components (Hour, Minute, Second) as given in the string variable, but it will have a different date. The Year, Month and Day components are not present in the string, so they will default to the date of DateTime.MinValue.Date. In order to compare correctly, you need to compare only the time parts:
bool isParsedGreater = parsedTime.Hours > DateT.Hours
&& parsedTime.Minutes > DateT.Minutes
&& parsedTime.Seconds > DateT.Seconds;
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a field returning a year and month value. For example, 20119 (2011 is year and 9 is for September). How could I compare that to the current year and month to get the difference in months? For example, in the same format the current year and month would be 20135, so the value I would be looking for would be 20. 20135 minus 20 months would be 20119. Not sure how to construct the formula to dynamically calculate the difference in months using date functions, perhaps.
Try this
DateTime x1 = DateTime.ParseExact("20119", "yyyyM", CultureInfo.InvariantCulture);
DateTime x2 = DateTime.ParseExact("20135", "yyyyM", CultureInfo.InvariantCulture);
int months = Math.Abs((x2.Month - x1.Month) + 12 * (x2.Year - x1.Year));
First I am assuming that by your question:
Single date months will have one digit
The value of the Year+Month is a string (if it is an int, throw a ToString() on the in value in the code below)
Your value thus will be 5-6 digits in length. You can perform the code below in less lines, but forgive my verbose answer - I will add extra code to make this more clear:
We can get the current date only as month year by getting using Date.Now
// Just want the month/year
DateTime currentDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
Now we can get your date for to test against the current year/month using a substring method (remember my assumption that we are dealing with a string value, and to convert ToString() if not).
// breaking out test date to year/month portions and saving as a new date time
string testDateValue = "20119";
int testDateYear = Convert.ToInt32(testDateValue.Substring(0, 4));
int testDateMonth = Convert.ToInt32(testDateValue.Substring(4));
DateTime testDate = new DateTime(testDateYear, testDateMonth, 1);
Now lets get the difference:
// get month dif - remove abs() if want negative if test date in future
int numberOfMonths = Math.Abs(((currentDate.Year - testDate.Year) * 12) +
(currentDate.Month - testDate.Month));
Now - if you want to compare 2 days in the yyyym format instead of using current date, just do the year/month conversion listed above and then perform the month dif formula on that.
Why not multiply the year by number of months in a year for each date field and then return the difference?
You can use the class DateDiff class from the Time Period Library for .NET, to calculate the months:
// ----------------------------------------------------------------------
public void CalcMonths( DateTime epoch )
{
DateDiff dateDiff = new DateDiff( DateTime.Now, epoch );
Console.WriteLine( "{0} months", dateDiff.Months );
// > 1 Year 4 Months 12 Days 12 Hours ago
} // CalcMonths
You can basically split the string.
int a = 201410;
int b= 20139;
int year1 = int.Parse(a.ToString().Substring(0,4));
int year2 = int.Parse(b.ToString().Substring(0,4));
int month1 = int.Parse(a.ToString().Substring(4));
int month2 = int.Parse(b.ToString().Substring(4));
//now construct a date for each
DateTime date1 = new DateTime(year1, month1, 1);
DateTime date2 = new DateTime(year2, month2, 1);
//then subtract them and make it months
int numberOfMonths = ((date1.Year - date2.Year) * 12) + date1.Month - date2.Month;
This is a code snippet from the solution posted on MSDN (link):
DateTime oldDate = new DateTime(2002,7,15);
DateTime newDate = DateTime.Now;
// Difference in days, hours, and minutes.
TimeSpan ts = newDate - oldDate;
// Difference in days.
int differenceInDays = ts.Days;
Should work for years/months as well (something like the following):
int differenceInMonths = (ts.Years *12 + ts.Months);
Hope this will help.
Rgds, AB
I have a DateTime object that is 10:00 AM
This time represents what time of day a report should be run.
I want to calculate the amount of time remaining from NOW until 10:00 AM
part of my confusion is NOW might be after 10:am or BEFORE 10am,
I keep playing around with TimeSpan, but my results are not quite right... I am sure this is simple, but it is one of those things I have been working of for a few hours and I need a push in the right direction...
I want the timespan object timeTillRun to be correct...here is what I have tried:
{
DateTime scheduledRun = DateTime.Today.AddHours(_timeToStart);//_timeToStart = 10
TimeSpan timeTillRun = DateTime.Now - scheduledRun;
}
This will work... but you need to reverse the order of subtraction:
TimeSpan timeTillRun = scheduledRun - DateTime.Now;
Note that if it's currently after 10AM, timeTillRun will be negative. You will presumably also need to check if the current time is on or after 10AM, then add 10 hours and one day to DateTime.Today to obtain the next run time. Alternatively, you could test if timeTillRun is negative; if so, just add one day to it (timeTillRun += new TimeSpan(1, 0, 0, 0)).
Try this
DateTime timeToStart = DateTime.Today.AddHours(10);
TimeSpan timeTillRun;
// Checking to see if current time is passed schedule run, if it is then we add a day (this is assuming this is run daily, if days are skipped like weekends for example then this would need some tweaking)
if (DateTime.Now > timeToStart)
timeTillRun = DateTime.Now.AddDays(1.0) - timeToStart;
else
timeTillRun = DateTime.Today - timeToStart;
double totalHoursRemaining = timeTillRun.TotalHours; // get total hours remaining
string prettyRemaining = String.Format("{0} day and {1} hours", timeTillRun.Days, timeTillRun.Hours); // can do some outputting here
I have a query that is calling an Oracle DB from C#. I want to write the query to get data that is, at most, 5 years old.
I currently have a hard coded value for public const int FIVE_YEARS_IN_DAYS = 1825;
But, this isn't correct because of leap years. Is there a function that will give me the correct number of days in the preceeding 5 years?
I think you want this:
DateTime now = DateTime.Now;
now.AddYears(-5).Subtract( now ).Days
DateTime now = DateTime.Now;
TimeSpan fiveYears = now.Subtract(now.AddYears(-5));
int numberOfDaysInLastFiveYears = fiveYears.Days;
This will correctly account for leap years. Doing this right now yields 1,826 days.