Get Current DateTime C# without hour - c#

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.

Related

Number of minutes until an unknown DateTime

If I have a DateTime variable that's set to the future, and I don't know if it's set to Utc or Local time, how can I find the number of minutes until this time? Something like this:
DateTime futureTime;
// futureTime is set to some value...
int minutesUntilFutureTime = futureTime - DateTime.Now;
You want a TimeSpan object
TimeSpan untilFutureTime = futureTime - DateTime.Now;
TimeSpan has a property called minutes and total minutes, total minutes is what you want.
int minutesUntilFutureTime = untilFutureTime.TotalMinutes;
doc https://learn.microsoft.com/en-us/dotnet/api/system.timespan?view=netframework-4.8
DateTime has a Kind property that allows you to determine whether or not the time is Local or UTC.
It also can be Unspecified in which case I think you just have to guess because you don't have enough information.
Another option could be to use the .ToLocalTime() method to force your DateTime to always be expressed a Local DateTime.
DateTime futureTime;
double minutesUntilFutureTime = (futureTime.ToLocalTime() - DateTime.Now).TotalMinutes;

Adding days to only date and then subtracting it from date in c#

I know this topic has already been discussed but I want to add days to only date, not the complete datetime and then I need to subtract it with date. What I have done till now is :
string endDate = DateTime.Now.AddDays(2).ToShortDateString();
Now this gives me string like 19-jan-17 which is great but when I want to subtract it with todays date, it gives error because the end date is in string. I tried below code:
TimeSpan diff = DateTime.Now.ToShortDateString() - endDate ;
or
TimeSpan diff = DateTime.Now.ToShortDateString() - Convert.ToDateTime(endDate)
or
TimeSpan diff = DateTime.Now.ToShortDateString() - Convert.ToString(endDate)
and if I change DateTime.Now.ToShortDateString() to DateTime.Now then it will also include time which I do not want. I just want to add days in date only and then subtract it with today's date.
Any suggestions. Please help.
Try this:
DateTime endDate = DateTime.Today.AddDays(2);
TimeSpan diff = DateTime.Today - endDate
The Today property will return only the date part (so time will be 00:00:00), but still in a DateTime struct, so you can get a TimeSpan from subtracting another DateTime from it.
Did you try doing the following?
string endDate = DateTime.Now.Date.AddDays(2);
Still, it is not clear why you have to do that. A bit of context would be great for proposing other solutions.
I join Federico, you need to use the Date property of the DateTime instance. It will return the 00:00:00 moment of the date.
One side note:
Just keep all dates in DateTime (e.g. do not convert them into strings) before calculating the diff.
e.g.:
TimeSpan diff = DateTime.Now.Date - endDate;
If you need the date part, you can use format strings after the calculation.
e.g.:
endDate.ToString("yyyy.MM.dd")

Convert datetime entered by user to UTC

The user enters a date and a time in separate textboxes. I then combine the date and time into a datetime. I need to convert this datetime to UTC to save it in the database. I have the user's time zone id saved in the database (they select it when they register). First, I tried the following:
string userTimeZoneID = "sometimezone"; // Retrieved from database
TimeZoneInfo userTimeZone = TimeZoneInfo.FindSystemTimeZoneById(userTimeZoneID);
DateTime dateOnly = someDate;
DateTime timeOnly = someTime;
DateTime combinedDateTime = dateOnly.Add(timeOnly.TimeOfDay);
DateTime convertedTime = TimeZoneInfo.ConvertTimeToUtc(combinedDateTime, userTimeZone);
This resulted in an exception:
The conversion could not be completed because the supplied DateTime did not have the Kind property set correctly. For example, when the Kind property is DateTimeKind.Local, the source time zone must be TimeZoneInfo.Local
I then tried setting the Kind property like so:
DateTime.SpecifyKind(combinedDateTime, DateTimeKind.Local);
This didn't work, so I tried:
DateTime.SpecifyKind(combinedDateTime, DateTimeKind.Unspecified);
This didn't work either. Can anyone explain what I need to do? Am I even going about this the correct way? Should I be using DateTimeOffset?
Just like all the other methods on DateTime, SpecifyKind doesn't change an existing value - it returns a new value. You need:
combinedDateTime = DateTime.SpecifyKind(combinedDateTime,
DateTimeKind.Unspecified);
Personally I'd recommend using Noda Time which makes this kind of thing rather clearer in my rather biased view (I'm the main author). You'd end up with this code instead:
DateTimeZone zone = ...;
LocalDate date = ...;
LocalTime time = ...;
LocalDateTime combined = date + time;
ZonedDateTime zoned = combined.InZoneLeniently(zone);
// You can now get the "Instant", or convert to UTC, or whatever...
The "leniently" part is because when you convert local times to a specific zone, there's the possibility for the local value being invalid or ambiguous in the time zone due to DST changes.
You can also try this
var combinedLocalTime = new DateTime((dateOnly + timeOnly.TimeOfDay).Ticks,DateTimeKind.Local);
var utcTime = combinedLocalTime.ToUniversalTime();

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

C# Getting Just Date From Timestamp

If I have a timestamp in the form: yyyy-mm-dd hh:mm:ss:mmm
How can I just extract the date from the timestamp?
For instance, if a timestamp reads: "2010-05-18 08:36:52:236" what is the best way to just get 2010-05-18 from it.
What I'm trying to do is isolate the date portion of the timestamp, define a custom time for it to create a new time stamp. Is there a more efficient way to define the time of the timestamp without first taking out the date, and then adding a new time?
DateTime.Parse("2010-05-18 08:36:52:236").ToString("yyyy-MM-dd");
You should use the DateTime type:
DateTime original = DateTime.Parse(str);
DateTime modified = original.Date + new TimeSpan(13, 15, 00);
string str = modified.ToString("yyyy-MM-dd HH:mm:ss:fff");
Your format is non-standard, so you'll need to call ParseExact instead of Parse:
DateTime original = DateTime.ParseExact(str, "yyyy-MM-dd HH:mm:ss:fff", CultureInfo.InvariantCulture);
You could use substring:
"2010-05-18 08:36:52:236".Substring(0, 10);
Or use ParseExact:
DateTime.ParseExact("2010-05-18 08:36:52:236",
"yyyy-MM-dd HH:mm:ss:fff",
CultureInfo.InvariantCulture)
.ToString("yyyy-MM-dd");
DateTime date;
if (DateTime.TryParse(dateString, out date))
{
date = date.Date; // Get's the date-only component.
// Do something cool.
}
else
{
// Flip out because you didn't get a real date.
}
Get the .Date member on the DateTime
DateTime date = DateTime.Now;
DateTime midnightDate = date.Date;
use it like this:
var x = DateTime.Now.Date; //will give you midnight today
x.AddDays(1).AddTicks(-1); //use these method calls to modify the date to whats needed.
The best (and fastest) way to do this is to convert the date to an integer as the time part is stored in the decimal part.
Try this:
select convert(datetime,convert(int, #yourdate))
So you convert it to an integer and then back to a data and voila, time part is gone.
Of course subtracting this result from the original value will give you the time part only.

Categories

Resources