un-representable DateTime - c#

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

Related

How to set time to Zeros in DateTime?

Lets say I have the following DateTime variable
DateTime CurDate = '26/3/2014 12:00:00 AM';
I'm wondering how can I set the CurDate so that the value will become 26/3/2014 00:00:00 AM
Note that I still want the time, but with all zeros.
**P/S: The reason for having all zeros is because the datetime value stored in SQL Server is 26/3/2014 00:00:00.000. I need to cast CurDate to have all zeros in order to match database data
You can simply use
CurDate.Date and that will give you '26/3/2012 00:00:00'
Try to format DateTime:
DateTime dt = new DateTime(2014, 06, 21, 0, 0, 0);
Console.WriteLine(dt.ToString("dd.MM.yyyy HH:mm:ss tt"));
Result:
21.06.2014 00:00:00
More informations:
http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
You could try this one:
// Parse the string you have, to create a datetime.
DateTime CurDate = DateTime.ParseExact('26/3/2014 12:00:00 AM',
"dd-MM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
// Create the datetime you want based on the CurDate
DateTime result = new DateTime(CurDate.Year, CurDate.Month, CurDate.Day, 0, 0, 0);
For more information about ParseExact please have a look here.
Nowhere, in SQL Server or in .NET dates hasn't any presentation. They are just an numeric value. Don't care about that, both the SQL Server and .NET so smart that can pass parameters without any confusion. Just pass parameters of the correct data type.
Use 24 Hour Format
DateTime CurDate = DateTime.Parse("3/26/2014 12:00:00 AM");
Console.WriteLine("12 Hour Format: " + CurDate.ToString("dd-MM-yyyy hh:mm:ss"));
Console.WriteLine("24 Hour Format: " + CurDate.ToString("dd-MM-yyyy HH:mm:ss"));
I know it's late but I think this was the proper answer for future references:
Console.WriteLine("Current Date with 0s on time part: " + DateTime.Now.ToString("yyyy-MM-dd 00:00:00.000"));
this.dtGelisSaati = DateTime.Now;
set curency time values
this.dtGelisSaati = DateTime.Today;
this ok. zero time values set.
Put .Date and get the date part with zero time part.
I use Linq as:
var list = Results.Where(x => x.ExpDate.Date >= From.Date && x.ExpDate.Date <= To.Date).ToList();

DateTime returns wrong date

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;

How to get the previous month date in asp.net

I need to get the previous months date in asp.net which means that if the current date is 5/2/2013 then I want to display the previous date as 5/1/2013. How to solve this?
Try this :
DateTime d = DateTime.Now;
d = d.AddMonths(-1);
The solution is to substract 1 month:
DateTime.Now.AddMonths(-1)
Or if not just build the datetime object from scratch:
var previousDate = DateTime.Now.AddMonth(-1);
var date = new DateTime(previousDate.Year, previousDate.Month, DateTime.Now.Day);
this time you are guaranteed that the year and month are correct and the day stays the same. (although this is not a safe algorithm due to cases like the 30th of march and the previous date should be 28/29th of February, so better go with the first sugeestion of substracting a month)
If you already have date time in string format
var strDate = "5/1/2013";
var dateTime = DateTime.ParseExact(strDate,
"dd/MM/yyyy",
CultureInfo.InvariantCulture);
var lastMonthDateTime = dateTime.AddMonths(-1);
else if you have DateTime object just call it's AddMonths(-1) method.

Merge 2 DateTime vars into one in C#

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

how to convert 24-hour format TimeSpan to 12-hour format TimeSpan?

I have TimeSpan data represented as 24-hour format, such as 14:00:00, I wanna convert it to 12-hour format, 2:00 PM, I googled and found something related in stackoverflow and msdn, but didn't solve this problem, can anyone help me? Thanks in advance.
Update
Seems that it's possible to convert 24-hour format TimeSpan to String, but impossible to convert the string to 12-hour format TimeSpan :(
But I still got SO MANY good answers, thanks!
(Summing up my scattered comments in a single answer.)
First you need to understand that TimeSpan represents a time interval. This time interval is internally represented as a count of ticks an not the string 14:00:00 nor the string 2:00 PM. Only when you convert the TimeSpan to a string does it make sense to talk about the two different string representations. Switching from one representation to another does not alter or convert the tick count stored in the TimeSpan.
Writing time as 2:00 PM instead of 14:00:00 is about date/time formatting and culture. This is all handled by the DateTime class.
However, even though TimeSpan represents a time interval it is quite suitable for representing the time of day (DateTime.TimeOfDay returns a TimeSpan). So it is not unreasonable to use it for that purpose.
To perform the formatting described you need to either rely on the formatting logic of DateTime or simply create your own formatting code.
Using DateTime:
var dateTime = new DateTime(timeSpan.Ticks); // Date part is 01-01-0001
var formattedTime = dateTime.ToString("h:mm tt", CultureInfo.InvariantCulture);
The format specifiers using in ToString are documented on the Custom Date and Time Format Strings page on MSDN. It is important to specify a CultureInfo that uses the desired AM/PM designator. Otherwise the tt format specifier may be replaced by the empty string.
Using custom formatting:
var hours = timeSpan.Hours;
var minutes = timeSpan.Minutes;
var amPmDesignator = "AM";
if (hours == 0)
hours = 12;
else if (hours == 12)
amPmDesignator = "PM";
else if (hours > 12) {
hours -= 12;
amPmDesignator = "PM";
}
var formattedTime =
String.Format("{0}:{1:00} {2}", hours, minutes, amPmDesignator);
Admittedly this solution is quite a bit more complex than the first method.
TimeSpan represents a time interval not a time of day. The DateTime structure is more likely what you're looking for.
You need to convert the TimeSpan to a DateTime object first, then use whatever DateTime format you need:
var t = DateTime.Now.TimeOfDay;
Console.WriteLine(new DateTime(t.Ticks).ToString("hh:mm:ss tt"));
ToShortTimeString() would also work, but it's regional-settings dependent so it would not display correctly (or correctly, depending on how you see it) on non-US systems.
TimeSpan represents a time interval (a difference between times),
not a date or a time, so it makes little sense to define it in 24 or 12h format. I assume that you actually want a DateTime.
For example 2 PM of today:
TimeSpan ts = TimeSpan.FromHours(14);
DateTime dt = DateTime.Today.Add(ts);
Then you can format that date as you want:
String formatted = String.Format("{0:d/M/yyyy hh:mm:ss}", dt); // "12.4.1012 02:00:00" - german (de-DE)
http://msdn.microsoft.com/en-us/library/az4se3k1%28v=vs.100%29.aspx
Try This Code:
int timezone = 0;
This string gives 12-hours format
string time = DateTime.Now.AddHours(-timezone).ToString("hh:mm:ss tt");
This string gives 24-hours format
string time = DateTime.Now.AddHours(-timezone).ToString("HH:mm:ss tt");
Assuming you are staying in a 24 hour range, you can achieve what you want by subtracting the negative TimeSpan from Today's DateTime (or any date for that matter), then strip the date portion:
DateTime dt = DateTime.Today;
dt.Subtract(-TimeSpan.FromHours(14)).ToShortTimeString();
Yields:
2:00 PM
String formatted = yourDateTimeValue.ToString("hh:mm:ss tt");
It is very simple,
Let's suppose we have an object ts of TimesSpan :
TimeSpan ts = new TimeSpan();
and suppose it contains some value like 14:00:00
Now first convert this into a string and then in DateTime
as following:
TimeSpan ts = new TimeSpan(); // this is object of TimeSpan and Suppose it contains
// value 14:00:00
string tIme = ts.ToString(); // here we convert ts into String and Store in Temprary
// String variable.
DateTime TheTime = new DateTime(); // Creating the object of DateTime;
TheTime = Convert.ToDateTime(tIme); // now converting our temporary string into DateTime;
Console.WriteLine(TheTime.ToString(hh:mm:ss tt));
this will show the Result as: 02:00:00 PM
Normal Datetime can be converted in either 24 or 12 hours format.
For 24 hours format - MM/dd/yyyy HH:mm:ss tt
For 12 hours format - MM/dd/yyyy hh:mm:ss tt
There is a difference of captial and small H.
dateTimeValue.ToString(format, CultureInfo.InvariantCulture);

Categories