I have 2 DateTime variables.
One is: DateTime date //this format is yyyymmdd
Second is: DateTime time // this format is hhmmtt (hour:min:tt)
How can I combine these 2 together? generate one DateTime variable.
var output = new DateTime(date.Year, date.Month, date.Day,
time.Hour, time.Minute, time.Second);
This only works for the two dates you listed, though, where one is the date and one is the time.
You should convert one of the DateTimes to a TimeSpan and add it to the second DateTime. Take the time-only DateTime. You can use its GetTicks method and pass it to a\the TimeSpan constructor.
DateTime day; //assumed set with the correct date
DateTime time; //assumed set with the relevant hour, minute, second
DateTime all = day.Date.Add(new TimeSpan(time.Hour, time.Minute, time.Second));
DateTime date = new DateTime(2012,12,04);
DateTime time = new DateTime(1,1,1,11,20,30);
DateTime combined = date.AddSeconds(TimeSpan.Parse(time.ToShortTimeString()).TotalSeconds);
Console.WriteLine(date);
Console.WriteLine(time);
Console.WriteLine(combined);
04.12.2012 00:00:00
01.01.0001 11:20:30
04.12.2012 11:20:00
Related
I must have built up such that I have a datetime which gets added antale day as it should go forward. and then I have time as it should set off in relation to 04/10/16 to 10/09/16
I do not care about the time which is in datetime. It should not I use for anything. What I need out of this is exactly how many days there are from that time.
Datetime dateString = "4/10/2016 8:30:52" //I pretend that it comes from the database, it was more in terms of see what come there.
DateTime dt = DateTime.Now.AddDays(5);
What I need out of this is that it tell me how many days there are in between the two datetime as I entered.
You can substract DateTime objects to obtain a TimeSpan:
Datetime dateString = DateTime.Parse("4/10/2016 8:30:52");
DateTime dt = DateTime.Now;
TimeSpan duration = dt-dateString;
From the TimeSpan object, you can get how many (full) days with :
int totalCompleteDays = (int)duration.TotalDays;
Or if you want a rounded results :
int roundedTotalDays = (int)Math.Round(duration.TotalDays);
DateTime objects support basic operators and will return TimeSpan objects.
DateTime DateTimeB = DateTime.Now.AddDays(5);
DateTime DateTimeA = DateTime.Now;
TimeSpan difference = DateTimeA - DateTimeB;
...
you can then use the TotalDays property of the timeSpan.
...
Console.out.WriteLine(difference.TotalDays);
How can I get a DateTime based on a string
e.g:
if I have mytime = "14:00"
How can I get a DateTime object with current date as the date, unless current time already 14:00:01, then the date should be the next day.
This is as simple as parsing a DateTime with an exact format.
Achievable with
var dateStr = "14:00";
var dateTime = DateTime.ParseExact(dateStr, "H:mm", null, System.Globalization.DateTimeStyles.None);
The DateTime.ParseExact() (msdn link) method simply allows you to pass the format string you wish as your parse string to return the DateTime struct. Now the Date porition of this string will be defaulted to todays date when no date part is provided.
To answer the second part
How can I get a DateTime object with current date as the date, unless
current time already 14:00:01, then the date should be the next day.
This is also simple, as we know that the DateTime.ParseExact will return todays date (as we havevnt supplied a date part) we can compare our Parsed date to DateTime.Now. If DateTime.Now is greater than our parsed date we add 1 day to our parsed date.
var dateStr = "14:00";
var now = DateTime.Now;
var dateTime = DateTime.ParseExact(dateStr, "H:mm", null, System.Globalization.DateTimeStyles.None);
if (now > dateTime)
dateTime = dateTime.AddDays(1);
You can use DateTime.TryParse(): which will convert the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.
string inTime="14:00";
if(DateTime.TryParse(inTime,out DateTime dTime))
{
Console.WriteLine($"DateTime : {dTime.ToString("dd-MM-yyyy HH:mm:SS")}");
}
Working example here
There is a datetime constructor for
public DateTime(
int year,
int month,
int day,
int hour,
int minute,
int second
)
So then parse the string to find the hours, minutes, and seconds and feed that into this constructor with the other parameters supplied by Datetime.Now.Day and so on.
I think you want to do something like this:
string myTime = "14:00";
var v = myTime.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
DateTime obj = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, int.Parse(v[0]), int.Parse(v[1]), DateTime.Now.Second);
I'm trying to get today's date
DateTime todayDateTime = new DateTime();
and I'm getting this:
{1/1/0001 12:00:00 AM}.
Why is this happening?
Use this
DateTime date = DateTime.Now;
Using new DateTime() creates a DateTime with a time of "0".
If you want todays date you need to use DateTime.Today if you want a DateTime object with a date of today and a time of 12:00:00 AM or DateTime.Now if you want a DateTime with the day and time of the moment you called DateTime.Now.
According to MSDN, the constructor for DateTime which takes in a long initializes by using the specified number of ticks since January 1st, 0001, so saying new DateTime(0) yields this time, not the current time.
Instead, use the static field DateTime.Now to get a DateTime representing the current system time.
In your question you are just initializing the Variable todayDateTime but you have never assigned (set it). This is why it is date ("null")/ beginning of our time calculations.
To actually get todays Date, you can use the following:
DateTime today = DateTime.Today;
first of all you need to assigned a value in the datetime.
just use something like this :
DateTime today = DateTime.Today;
I'm trying to merge today's date with an existing time value I have stored in a sql server database. Let me give you an example:
ClientTradedTime = "16:52:01" (this is of type timespan)
I want to merge that value with today's date in variable of type DateTime to use it else where, example:
DateTime mydate;
mydate = "2014-02-04 16:52:01" (this is what I want to see when I store it in my database)
How can I solve this problem?
Just Datime.Add() the TimeSpan to the DateTime's Date property and you will get your desired DateTime like:
DateTime updatedDt = mydate.Date.Add(ClientTradedTime);
Consider the following example:
DateTime myDate = DateTime.Now;
TimeSpan ClientTradedTime = new TimeSpan(16, 52, 51);
DateTime updatedDt = myDate.Date.Add(ClientTradedTime);
This will give you:
updatedDt = {04/02/2014 4:52:51 PM}
myDate.Date would give you DateTime with Time set to 00:00:00 and then you can add your TimeSpan to it.
I have method which expects two datetime parameters
public void SomeReport(DateTime TimeFrom, DateTime TimeTo)
{
// ommited
TimeFrom.ToString("ddMMyy"), TimeTo.ToString("ddMMyy")));
// ommited
}
When I'm sending this params
DateTime TimeTo = DateTime.Now;
DateTime TimeFrom = new DateTime().AddHours(-1);
This error occured:
System.ArgumentOutOfRangeException : The added or subtracted value results in an un-representable DateTime.
What can be the problem?
new DateTime() is 01/01/0001 00:00:00 which is also DateTime.MinValue.
You are subtracting one hour from that.
Guessing you are trying to subtract an hour from the TimeTo value:
var TimeFrom = TimeTo.AddHours(-1);
new DateTime() returns the minimum representable DateTime; adding -1 hours to this results in a DateTime that can't be represented.
You probably want DateTime TimeFrom = TimeTo.AddHours(-1);
try:
DateTime TimeTo = DateTime.Now;
DateTime TimeFrom = TimeTo.AddHours(-1);
creating a DateTime with new DateTime() gives you a DateTime with DateTime.MinValue... from this you actually can't subtract anything... otherwise you get the exception you got... see MSDN
Look you date or time data .There not enough digits for date or time Example date must be 8 digit 20140604 and time 6 digit like this 180203.For this reason you are getiing error.
i get this error too and find time 18000 and change this to 180000 problem solved.
In your case TimeFrom holds the datetime from which -1 can not be added. You can either invoke
DateTime TimeFrom = TimeTo .AddHours(-1);
or
DateTime TimeFrom = new DateTime().now.AddHours(-1);
Both of them yield the same result.
In my error, I used the time as 24:00 instead of 00:00