Empty datetime in the report - c#

I face the following problem :
Sometimes the value of my trans_in(DateTime) in my database is :1900-01-01 00:00:00.000
and it appears in my telerik report like this 12:00 AM i want to show the textbox empty instead so i create the following custom method :
public static string NotAttend(DateTime trans_in)
{
if (trans_in == null || trans_in.ToString().Trim() == "1900-01-01 00:00:00.000")
{
return string.Empty;
}
else
return trans_in.ToShortTimeString();
}
and bind the textbox like this :
= OvertimeReports.CustomExpressions.NotAttend(Fields.trans_in)
but this didn't fix my problem still appear 12:00 AM !!

Your trans_in.ToString() would return you the string representation of your DateTime object based on your current culture, its better if you check your DateTime like:
public static string NotAttend(DateTime trans_in)
{
if(trans_in == new DateTime(1900, 1, 1))
{
return string.Empty;
}
else
return trans_in.ToShortTimeString();
}

Try to compare the trans_in with default(new DateTime())
You shouldn't compare a date with a String without formatting it
reference:
http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/d0f4578c-0585-4f38-95be-569a90ebeb21/
edit: i'm seeing here you'd best compare with DateTime.MinValue
Determining whether the new date is the default new DateTime() or not

You can provide a format to your DateTime by using overridden function of DateTime.ToString(). HH means time in 24 HRS where hh means 12 HRS format :
public static string NotAttend(DateTime trans_in)
{
if (trans_in == null ||
trans_in.ToString("yyyy-MM-dd HH:mm:ss.fff") == "1900-01-01 00:00:00.000")
{
return string.Empty;
}
else
return trans_in.ToShortTimeString();
}

The problem what you have here is more of a formatting issue with the .ToString conversion
Try using the specific format you need in the .ToString overload for this
trans_in("yyyy-M-d HH:mm:ss.fff")
So in this HH case you would have it as 00:00 instead of 12:00
A better way would be to compare it as DateTime make a DateTime obj for 1900-1-1 then compare it with trans_in.Date part which would not involve this string formatting issues

Related

Get only the Date without Time from DateTime

i came across a situation that, i need to get only the Date out from DateTime.
i am having a DateTime? StartDate property (Nullable) used to hold the date value
i tried below,
var d = Convert.ToDateTime(StartDate).Date;
but its returning me d as eg. 6/22/2006 12:00:00AM
after doing var d = Convert.ToDateTime(StartDate).Date.ToString("d");
i'm able to get d as 6/22/2006..but i dont want to convert my DateTime? to String
is their any way to get only the Date without using the ToString("d")?
Use the Date property to get the Date component of DateTime instance:
DateTime dateTimeNow = DateTime.Now;
DateTime datePartOnly = dateTimeNow.Date; // Return 00/00/0000 00:00:00
With this approach, Date property will return the date at midnight. So the time part will be 00:00:00 in this case.
There are couple of alternate ways to get the just the Date part, but the return type of it will be a string:
1.) Using .ToString(string? format) where format can be standard or custom format string
string dateOnlyString = dateTimeNow.ToString("dd/MM/yyyy");
//Can also use .ToString("dd-MM-yyyy");
2.) Using .ToShortDateString() to return a culture sensitive date string
string dateOnlyString = dateTimeNow.ToShortDateString();
//Returns M/d/yyyy for "en-US" culture
//Returns yyyy/M/d for "ja-JP" culture
Reference: here.
try this:
string x = DateTime.Now.ToShortDateString().
this will get the date dd/mm/yy given to the string x.
I think you question is sort of... moot.
You ask for a date without a time, but get a DateTime, which has both. I really don't think that should be a problem in most cases though:
If you create a DateTime with a certain date, and compare it to another date, and both of these have their time set to midnight, your comparisons will be valid and correct. Eg:
var yesterday = new DateTime(2014, 3, 10);
var today = new DateTime(2014, 3, 11);
var tomorrow = new DateTime(2014, 3, 12);
Comparing and sorting these will work as you expect, and so will the following:
if(today == DateTime.Today){
Console.WriteLine("Today is the day!");
}
In other words, you should be perfectly fine just pretending like the time-part does not exist.
Also, as you touched upon yourself in the OP, you can use the property Date if you want to make sure to avoid any time-component:
// Note the addition of hours, minutes and seconds:
var today = new DateTime(2014, 3, 11, 14, 35, 33);
if(today == DateTime.Today){
Console.WriteLine("This never happened...");
}
if(today.Date == DateTime.Today){
Console.WriteLine("...But today is still the day!");
}
In C# 10 you can use DateOnly.
DateOnly date = DateOnly.FromDateTime(DateTime.Now);
A DateTime does have both a date and a time. You can decide with yourself that in a specific property you well never use the date part. It will just be 12:00 AM, but you won't use it.
In some situations it can be useful to write your own type that can never hold a time-of-day component. Here is a start:
struct Date : IFormattable
{
readonly DateTime value;
public Date(DateTime dateAndTime)
{
value = dateAndTime.Date;
}
public string ToString(string format, IFormatProvider formatProvider)
{
return value.ToString(format ?? "d", formatProvider);
}
public string ToString(string format)
{
return ToString(format, null);
}
public string ToString(IFormatProvider formatProvider)
{
return ToString(null, formatProvider);
}
public override string ToString()
{
return ToString(null, null);
}
public static implicit operator DateTime(Date date)
{
return date.value;
}
}
The field value does hold the 12 AM thing, but it is private and is not seen from the outside. The overloads of ToString() make sure that unless something else is requested, the Date is written out with the short date format of the current culture.

Date not in correct format

I have a function that checks for null values then converts dates if they are not null
the below function just had "08/09/13" sent to it (English format) and i got "String was not recognized as a valid DateTime."
anyone help me as to why? do i need to tell the something somewhere is uses English format?
Thanks
public static DateTime DateTimeCheck(object objDateTime)
{
if (objDateTime == null || objDateTime == "")
return default(DateTime);
return Convert.ToDateTime(objDateTime);
}
I don't understand why you passed an object as a parameter instead of string first of all.
Try this instead;
public static DateTime DateTimeCheck(object objDateTime)
{
...
return DateTime.ParseExact(objDateTime.ToString(),"dd/MM/yy",CultureInfo.InvariantCulture);
}
Of course, this throws exception if your object is not formatted same as with "dd/MM/yy".
Take a look at;
Custom Date and Time Format Strings
You can use the overloaded method that accepts the culture information:
Convert.ToDateTime(o, new CultureInfo("en-Gb"));
To get or set the current culture you can use:
System.Threading.Thread.CurrentThread.CurrentCulture
You might be in a different culture with a different default date format. However you can use ParseExact to parse in the expected format. For example:
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result = DateTime.ParseExact("25/12/82","dd/MM/yy",provider);
I know this not what you are looking for but that's how to be sure that some object has date time value in it something like that :
public static DateTime DateTimeCheck(object objDateTime)
{
DateTime dateTime ;
if (objDateTime != null)
{
if (DateTime.TryParse(objDateTime.ToString(), out dateTime))
{
return Convert.ToDateTime(objDateTime);
}
}
return default(DateTime);
}
Try this:
DateTime.ParseExact((string)objDateTime,"dd/MM/yyyy",CultureInfo.InvariantCulture);

Converting DateTime [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to convert DateTime object to dd/mm/yyyy in C#?
I'm new to c# and was hoping someone could help me clean up some code.
I have the following method which converts a DateTime to a custom Event string e.g. 30th of Jan 2012 is converted to 201201 (ignores the day)
public ConvertToEventDate(DateTime date)
{
var year = date.Year.ToString();
var month = date.Month.ToString();
month = month.Length == 2 ? month : "0" + month;
return year + month;
}
I was wondering if there is a better way of doing this conversion.
I'd do this;
public string ConvertToEventDate(DateTime date)
{
return date.ToString("yyyyMM");
}
you can also put this into an Extension method like this;
public static class ExtenstionMethods
{
public static string ToEventDate(this DateTime date)
{
return date.ToString("yyyyMM");
}
}
and then call it ike this;
DateTime date = new DateTime(2012, 30, 1);
date.ToEventDate();
as opposed to this;
ConvertToEventDate(date);
public string ConvertToEventDate(DateTime date)
{
return date.ToString("yyyyMM", CultureInfo.InvariantCulture);
}
Have a look at the custom formatting strings docs
Others have suggested ToString("yyyyMM") which is basically there - but I would suggest you probably want to specify the invariant culture. Otherwise if the thread's current culture uses a non-Gregorian calendar, you could end up with a month/year you're not expecting. So I'd use:
string text = date.ToString("yyyyMM", CultureInfo.InvariantCulture);
See the documentation for custom date and time format strings for more information if you want to change the exact format later.
Try
return date.ToString("yyyyMM");

How to check for valid Date in yyyyMM format

I have an internal business process that my finance dept runs. To kick it off they input a Date in the format of yyyyMM or 201009. I want to check for a valid date from that string but so far I got nothing.
I am currently exploring breaking the string up, taking the first 4 and checking that they are between 1990 and 2050(as example) and then the last 2 and checking that it is between 01 and 12.
Is there a better way?
You can use DateTime.TryParseExact to see if it can be parsed correctly:
bool isValid = false;
DateTime dateValue;
if(DateTime.TryParseExact("201009", "yyyyMM", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dateValue))
{
// DateTime parsed, dateValue contains the parsed DateTime
// Can validate dateValue against business rules at this point
isValid = (dateValue <= DateTime.Now && dateValue >= DateTime.Now.AddYears(-5));
}
If you would rather get an exception, you can use DateTime.ParseExact:
// Next line throws exception if format not correct
DateTime.ParseExact("201009", "yyyyMM", CultureInfo.InvariantCulture);
You can use a regular expression:
if (Regex.IsMatch(input, #"^(199\d|20[0-5]\d)(0[1-9]|1[0-2])$")) {
// valid input between 199001 and 205912
}
I would go with DateTime.ParseExact:
DateTime d = DateTime.ParseExact("201009", "yyyyMM", System.Globalization.CultureInfo.InvariantCulture);
The problem here is that the format "yyyyMM" cannot represent a specific DateTime. So the parsing methods built in to DateTime will do you no good.
Update: Never mind; I stand corrected. DateTime.TryParseExact will work just fine (which is ironic, if you ask me); it'll interpret your string to represent the first day of the given month.
I would do what you're describing: parsing the string into the two numeric components and simply compare those values to whatever range you require them to fall within.
I'd be tempted perform this as a number range problem:
UInt32 val;
if (input.Length != 6
|| !UInt32.TryParse(input, out val)
|| val > 205012
|| val < 199001
|| val % 100 > 12
|| val % 100 == 0) {
// Invalid...
}

Convert the TimeSpan datatype to DateTime?

I'm converting a small MSAccess application to a web-based ASP.NET app, using C# 3.5. I was wondering what's the best way to work with dates in C#, when converting some of this VBA code over to C#.
Here is an example of the VBA Code:
Coverage1=IIf(IsNull([EffDate1]),0,IIf([CurrDate]<=[EndDate1],[CurrDate]-[EffDate1],[EndDate1]-[EffDate1]+1))
Here is what my current C# code looks like with the errors denoted in the commented code:
public DateTime CalculateCoverageOne(DateTime dateEffDateOne, DateTime dateCurrentDate, DateTime dateEndDateOne)
{
if (dateCurrentDate.Date <= dateEndDateOne.Date)
{
return null; //Get "cannot convert null to System.DateTime because it is a non-nullable value type" error
}
else
{
if (dateCurrentDate.Date <= dateEndDateOne)
{
return dateCurrentDate.Subtract(dateEffDateOne); //Gets error "cannot implicitly convert system.timepsan to system.datetime
}
else
{
return dateEndDateOne.Subtract(dateEffDateOne.AddDays(1)); //Gets error "cannot implicitly convert system.timepsan to system.datetime
}
}
}
cannot convert null to System.DateTime because it is a non-nullable value type" error
The DateTime type is a value type, which means that it cannot hold a null value. To get around this you can do one of two things; either return DateTime.MinValue, and test for that when you want to use the value, or change the function to return DateTime? (note the question mark), which is a nullable DateTime. The nullable date can be used like this:
DateTime? nullable = DateTime.Now;
if (nullable.HasValue)
{
// do something with nullable.Value
}
cannot implicitly convert system.timepsan to system.datetime
When you subtract a DateTime from another DateTime, the result is a TimeSpan, representing the amount of time between them. The TimeSpan does not represent a specific point in time, but the span itself. In order to get the date, you can use the Add method or the Subtract method overload of a DateTime object that accepts a TimeSpan. Exactly how that should look I can't say, since I don't know what the different dates in your code represent.
In the last case, you can simply use the return value from the AddDays method, but with a negative value (in order to subtract one day, instead of adding one):
return dateEffDateOne.AddDays(-1);
It looks like your VB is actually returning a time span, presumably in days. Here's the closest direct translation:
public TimeSpan CalculateCoverageOne(DateTime EffDate1, DateTime CurrDate, DateTime? EndDate1)
{
return (EndDate1 == null) ? TimeSpan.Zero :
(CurrDate < EndDate1) ? (CurrDate - EffDate1) :
(EndDate1.AddDays(1) - EffDate1);
}
If instead you just wanted a count of days, just return the TimeSpan's Days property:
public int CalculateCoverageOne(DateTime EffDate1, DateTime CurrDate, DateTime? EndDate1)
{
return ((EndDate1 == null) ? TimeSpan.Zero :
(CurrDate < EndDate1) ? (CurrDate - EffDate1) :
(EndDate1.AddDays(1) - EffDate1)).Days;
}
And for good measure, this is how I would clean up your final version:
public int CalculateCoverageOne(DateTime dateCurrentDate, DateTime dateEffectiveDate, DateTime dateEffDateOne, DateTime dateEndDateOne)
{
TimeSpan ts;
if (dateEffDateOne == DateTime.MinValue)
{
ts = TimeSpan.Zero;
}
else if (dateEffectiveDate <= dateEndDateOne)
{
ts = dateCurrentDate - dateEffDateOne;
}
else
{
ts = (dateEndDateOne - dateEffDateOne) + new TimeSpan(1, 0, 0, 0);
}
return ts.Days;
}
Get the TimeSpan, then subtract that from the DateTime to get the date you want. For your inner IF statement, it would look like this:
TimeSpan estSpan = dateCurrentDate.Subtract(dateEffDateOne);
return dateCurrentDate.Subtract(estSpan);
EDIT: You may also want to return DateTime.MaxValue and have the calling function check for the max value, instead of returning null.
DateTime is a value type. So, you cannot assign null to DateTime.
But you can use a special value like DateTime.MinValue to indicate whatever you were trying to indicate by null.
DateTime represents a date (and time), like "July 22, 2009". This means, you shouldn't use this type to represent time interval, like, "9 days". TimeSpan is the type intended for this.
dateCurrentDate.Subtract(dateEffDateOne) (or, equivalently, dateCurrentDate-dateEffDateOne) is a difference between two dates, that is, time interval. So, I suggest you to change return type of your function to TimeSpan.
TimeSpan is also a value type, so you could use, for instance, TimeSpan.Zero instead of null.
After some excellent answers (I've up-voted you guys), I've finally hammered out what I think is my answer. Turns out that returning an int, as the number of days, is what worked for me in this situation.
Thanks everyone, for providing your awesome answers. It helped me get on the right track.
public int CalculateCoverageOne(DateTime dateCurrentDate, DateTime dateEffectiveDate, DateTime dateEffDateOne, DateTime dateEndDateOne)
{
//Coverage1=
//IIf(IsNull([EffDate1]),0,
//IIf([CurrDate]<=[EndDate1],
//[CurrDate]-[EffDate1],
//[EndDate1]-[EffDate1]+1))
if (dateEffDateOne.Equals(TimeSpan.Zero))
{
return (TimeSpan.Zero).Days;
}
else
{
if (dateEffectiveDate <= dateEndDateOne)
{
return (dateCurrentDate - dateEffDateOne).Days;
}
else
{
return (dateEndDateOne - dateEffDateOne).Add(new TimeSpan(1, 0, 0, 0)).Days;
}
}
}

Categories