Easily calculate the time before midnight in C# - c#

I have a function which is already compact, i wanted to know if there was better (like a DateTime functionality already included).
Currently i use this:
DateTime today = DateTime.Now;
DateTime tomorrow = new DateTime(today.Year, today.Month, today.Day, 0, 0, 0).AddDays(1);
double remaining = (tomorrow - today).TotalMilliseconds;
Thank for reading.

You can simplify the tomorrow value by just doing this and taking the benefit of DateTime.Today:
DateTime tomorrow = DateTime.Today.AddDays(1);
So your code will be easy to read:
DateTime today = DateTime.Now;
DateTime tomorrow = DateTime.Today.AddDays(1);
double remaining = (tomorrow - today).TotalMilliseconds;

You can create extension for DateTime
public static class DateExtensions
{
public static double GetNextDayRemainingMs(this DateTime dateTime)
{
return (dateTime.AddDays(1).Date - dateTime).TotalMilliseconds;
}
}
Usage
DateTime.Now.GetNextDayRemainingMs();

You can try following code
(DateTime.Today.AddDays(1)-DateTime.Now).TotalMilliseconds

Instead of defining instance for tomorrow variable you can use .AddDate(1).Date property
.AddDate(1) will add one day to DateTime.Now and .Date property
will give you only date and sets time to 00.
DateTime today = DateTime.Now;
double remaining = (today.AddDate(1).Date - today).TotalMilliseconds;
Or (Elegant way)
You can use Today property of DateTime.
An object that is set to today's date, with the time component set to
00:00:00.
double remaining = (DateTime.Today.AddDays(1)-DateTime.Now).TotalMilliseconds

Related

Get Current DateTime C# without hour

Hi I currently have a TimePicker. It returns an object TimeSpan.
What I need to do is to set a DateTimeOffset that is equal to current date plus the TimeSpan from the TimePicker.
How can I actually get the current DateTimeOffset.now that doesn't have a Time on it, only the Date so that I can add the offset to it.
Thanks
As in DateTime object you have a Date property, it returns date part without time (it means time is 00:00:00).
DateTime today = DateTimeOffset.Now.Date;
DateTime result = today + yourTimeSpan;
With this solution will lost Offset information (because Date is a DateTime). To keep it you just need to subtract time part:
DateTimeOffset now = DateTimeOffset.Now;
DateTimeOffset result = now - now.Time + yourTimeSpan;
Or with constructor:
DateTimeOffset now = DateTimeOffset.Now;
DateTimeOffset result = new DateTimeOffset(now.Date + yourTimeSpan, now.Offset);
Can you not just .Date it?
var a = DateTimeOffset.Now.Date;
try using:
DateTime.Today
instead of Now.

Alternative Datetime.Now with only time (21:10)

I was wondering if there's a method or anything which will provide me the current systemtime without the date. I need to use this in a formula and if i want to use the DateTime.NowI have to String.Split this string before I can convert this to a Int.
example: It's 5pm
I want:
'17:00', '5:00', '1700', '500'
Not:
'17:00 PM 29/03/2013'
A DateTime holds the hour and minutes as properties.
var now = DateTime.Now;
var minutes = now.Minute;
var hours = now.Hour;
why cannot you simply format your date i.e.
string CurrentTime = DateTime.Now.ToString("hh:mm:ttt");
I guess what you are looking for is how to format a DateTime correctly.
Look here or here for how this is done.
You could use TimeOfDay. Basically it extracts the time part of a DateTime:
DateTime now = DateTime.Now;
TimeSpan time = now.TimeOfDay;
Do note that unlike the DateTime.Date property, DateTime.TimeOfDay returns a Timespan, not a DateTime.
for "1700" :
date.ToString('HHMM');
Use the DateTime.ToString method:
DateTime dt = DateTime.Now; // Suppose it is currently 5pm
dt.ToString("HH:mm"); // 17:00
dt.ToString("h:mm"); // 5:00
dt.ToString("HHmm"); // 1700
dt.ToString("hmm"); // 500

How to set current time to a value

I was just wondering if there is a way to get the current time and set it into a value.
If its 12:06 AM.. I want to get that time and set it into currentTime.
Example
float currentTime = 0;
currentTime = 12.06;
As others have mentioned, the DateTime class would be ideal for this, and to work out the difference between 2 date/times:
DateTime end = DateTime.Now;
DateTime start = new DateTime(2011, 12, 5, 12, 6,0);
double hours = (end - start).TotalHours;
The subtraction of DateTime objects results in a TimeSpan object that you can use to see the hours/minutes etc.
try DateTime class
DateTime dt = DateTime.Now;
Is this what you're looking for?
DateTime currentTime;
currentTime = DateTime.Now;
Don't use floats or strings. You can do all kinds of cool things using DateTime.
Here's how you'd get the hours that someone worked:
var clockIn = new DateTime(2011,12,4,9,0,0); // December 4th, 9 AM
var clockOut = new DateTime(2011,12,4,17,0,0); // December 4th, 5 PM
var duration = clockOut - clockIn; // TimeSpan
Console.Write(duration.TotalHours); // 8
A few people have mentioned how, but as a 'better' recommendation you should use
DateTime currentTime = DateTime.UtcNow
Otherwise you have issues when the clocks go back, if your timing code is run on those days. (plus it is far easier to alter the UTC time to local time than it is to convert a '1am' to UTC (as there will be two of them when the clocks go back)
Well if you really what it as a float then try:
var currentDate = DateTime.Now;
float currentTime = float.Parse((currentDate.Hour > 12 ? currentDate.Hour -12 :
currentDate.Hour) + "." + currentDate.Minute);
I wouldn't recommend comparing dates or time with floats. A better options would be to use timespans.
You should be using a Timespan instance for time related values, you can use the flexibility to get the required values like
TimeSpan ts = DateTime.Now.TimeOfDay;
ts.ToString("hh:mm") // this could be what you are looking for
You could then use ts.TotalHours which would give you fractional hours (as a double) else you could construct a string specifically using ts.Hours ..ts.Minutes play around and it could be prove useful.
Try the following:
DateTime StartTime=StartTime value;
DateTime CurrentTime=DateTime.Now;
TimeSpan dt = CurrentTime.Subtract(StartTime);
In dt you will get a working time period.
If you want to have the difference between two times, then do this:
DateTime dateOne = DateTime.Parse(enteredTime);
DateTime dateTwo = DateTime.Now;
TimeSpan difference = dateOne - dateTwo;

Join Date and Time to DateTime in C#

I am retrieving data from an iSeries where there is a separate date and time fields. I want to join them into a DateTime field in my C# project. I don't see a way to add just a time to a DateTime field. How would you suggest accomplishing this?
You can do this quite easily:
DateTime dateOnly;
DateTime timeOnly;
...
DateTime combined = dateOnly.Date.Add(timeOnly.TimeOfDay);
TimeOfDay returns a TimeSpan, which you then add to the date.
Edit (thanks to commenters below) - to be safe, use dateOnly.Date to ensure the date part only.
How are they being stored? Assuming that the date portion is being stored as a DateTime of midnight of the day in question and the time is a TimeSpan, you can just add them.
DateTime date = ...;
TimeSpan time = ...;
DateTime result = date + time;
You could easily construct a TimeSpan from your "time" field.
Once you have that, just do:
TimeSpan time = GetTimeFieldData();
dateField = dateField.Add(time);
Datetime date = new DateTime(Date1.Year, Date1.Month, Date1.Day, Time1.Hour, Time1.Minute, Time1.Second);
You can add a TimeSpan to a DateTime and write something like this.
// inside consuming function
ISeriesObject obj = getMyObject();
DateTime dt = getDate(obj) + getTime(obj);
private DateTime getDate(ISeriesObject obj)
{
//return a DateTime
}
private TimeSpan getTime(ISeriesObject obj)
{
//return a TimeSpan
}
My answer addresses joining two objects of DateOnly and TimeOnly in .NET 6:
DateOnly orderDate = ...
TimeOnly orderTime = ...
DateTime orderDateTime = orderDate.ToDateTime(orderTime);
This should do:
var output = date.Date + time.TimeOfDay;
or
var output = new DateTime(date.Year, date.Month, date.Day,
time.Hour, time.Minute, time.Second);
suppose that both variable date and time are both of Type DateTime
Note that adding the time to the date is not your biggest problem here. As #Reed Copsey mentioned, you just create a DateTime from the date and then .Add the time.
However, you need to make sure that the iSeries date and time (a Unix time most probably) are in the same representation as the .Net representation. Thus, you most probably need to convert it by adding it to a Jan 1, 1970 DateTime as well.
Cant you simply format the date part and time part as separate strings, then join them together? Then you can parse the string back to a DateTime object

DateTime convert to Date and then back to DateTime in C#

I use this to convert DateTime value into Date and then I add 00:00:00 and 23:59:59 to make sure whole day is taken into consideration when counting stuff. I'm pretty sure it's wrong way of doing things. What would be the right way?
DateTime varObliczOd = DateTime.Parse(dateTimeWycenaPortfelaObliczDataOd.Value.ToShortDateString() + " 00:00:00");
DateTime varObliczDo = DateTime.Parse(dateTimeWycenaPortfelaObliczDataDo.Value.ToShortDateString() + " 23:59:59");
if dateTimeWycenaPortfelaObliczDataOd is of type DateTime, You can use:
dateTimeWycenaPortfelaObliczDataOd.Date
to get the date part only (time will be 00:00:00...).
If you want to get the very last tick of the date, you can use:
dateTimeWycenaPortfelaObliczDataOd.Date.AddDays(1).AddTicks(-1)
but you really better work with the next date (.AddDays(1)).
In any case, there is no need to convert to string and back to DateTime.
DateTime objects have a Date property which might be what you need.
You can use the following properties / methods on a DateTime object to get your values :
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd.Date;
DateTime varObliczDo = dateTimeWycenaPortfelaObliczDataOd.AddDayes(1).AddTicks(-1);
It would help to know why you're needing it, but this would work.
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd.Date;
DateTime varObliczDo = varObliczOd.AddDays(1).AddSeconds(-1);
Using the Date attribute and then manipulating them directly to create the required time component - no need to bother with parsing and conversion.
You could use the Date property of the DateTime object to accomplish what you need.
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd.Value.Date;
DateTime varObliczDo = dateTimeWycenaPortfelaObliczDataDo.Value.Date.AddDays(1);
If you really want it to end at 23:59:59 you can do:
DateTime varObliczDo = dateTimeWycenaPortfelaObliczDataDo.Value.Date.AddDays(1).AddSeconds(-1);
Will set varObliczDo to be your ending date with no time plus one day (at midnight). So if dateTimeWycenaPortfelaObliczDataDo was 2010-03-05 16:12:12 it would now be 2010-03-06 00:00:00.
Something like this maybe? I've typed this out of my head, there are probably some mistakes in the code.
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd.AddSeconds(-dateTimeWycenaPortfelaObliczDataOd.Seconds).AddMinutes(-dateTimeWycenaPortfelaObliczDataOd.Minutes).AddHours(-dateTimeWycenaPortfelaObliczDataOd.Hours);
DateTime varObliczDo = new DateTime(dateTimeWycenaPortfelaObliczDataDo.Year, dateTimeWycenaPortfelaObliczDataDo.Month, dateTimeWycenaPortfelaObliczDataDoDay, 23, 59, 59);
DateTime newDate = new DateTime( oldDate.Year, oldDate.Month, oldDate.Day, 23, 59,59 )
DateTime newDate = new DateTime( oldDate.Year, oldDate.Month, oldDate.Day, 0, 0, 0 )
You could work with TimeSpan:
DateTime varObliczOd = dateTimeWycenaPortfelaObliczDataOd - new TimeSpan(dateTimeWycenaPortfelaObliczDataOd.Hours, dateTimeWycenaPortfelaObliczDataOd.Minutes, dateTimeWycenaPortfelaObliczDataOd.Seconds);
Like that you avoid at least the parsing, which can fail depending on the local culture settings.

Categories

Resources