c# creating datetime object without time [duplicate] - c#

This question already has answers here:
How to remove time portion of date in C# in DateTime object only?
(43 answers)
Closed 6 years ago.
I am trying to load some dates from a database, but i dont want to create a datetime object with time, i only want the date. I have tried with
var date = value.Date; it doesn't work. I have seen a lot of methods that basically format the date to show it as a string and i don't want to do that, because than i have to load all the data into the grid manually. I hope someone can help me. Here is the code
DateTime startDate = (DateTime)row["Course_StartDate"];
DateTime endDate = (DateTime)row["Course_EndDate"];

Do you need to use any of the functionality of DateTime, such as comparing dates or adding/subtracting days from a date? If not, you can probably just make your variables strings instead of DateTimes:
string startDate = ((DateTime)row["Course_StartDate"]).ToShortDateString();
string endDate = ((DateTime)row["Course_EndDate"]).ToShortDateString();
Edit: Since you do need to compare times, you could use a second property that returns the equivalent value as you need it:
DateTime startDate = new DateTime();
DateTime endDate = new DateTime();
string startDateString
{
get
{
return startDate.ToShortDateString();
}
}
string endDateString
{
get
{
return endDate.ToShortDateString();
}
}
private void LoadMethod()
{
startDate = (DateTime)row["Course_StartDate"];
endDate = (DateTime)row["Course_EndDate"];
}
Then you can do your math with the DateTime objects, and use the string objects in your table.

If you are talking about DataGridView, change the Column Format (DefaultCellStyle > Format) to MM/dd/yyyy

Related

C# DatePicker convert to DateTime and calculate the Age [duplicate]

This question already has answers here:
A property or indexer may not be passed as an out or ref parameter
(9 answers)
Closed 4 years ago.
I have a DatePicker(CPTestDP) in our WPF window, and the date picked is saved into SQL datebase as text. I would like to use calculate the Age(how many days) based on today's date by below code. But it turns error at CFTestDP.SelectedDate.
The error message says:
A property or indexer may not be passed as an out or ref parameter.
Could anyone help please? Much appreciate.
DateTime thisDay = DateTime.Today;
DateTime startDay = DateTime.TryParse(CFTestDP.SelectedDate, out CFTestDP.SelectedDate);
TimeSpan dateAge = thisDay - startDay;
txtAge.Text = string.Format("{dd}", dateAge);
As I have seen in the documentation you should pass as second parameter in the TryParse a reference to a variable of type DateTime and it will return a boolean that tells you if the parse was ok or not. So your code should be like this:
DateTime thisDay = DateTime.Today;
DateTime startDay;
bool result = DateTime.TryParse(CFTestDP.SelectedDate, out startDay);//CFTestDP.SelectedDate should be string
if(result)
{
TimeSpan dateAge = thisDay - startDay;
txtAge.Text = string.Format("{dd}", dateAge);
}
else
{
//Unable to parse
}
Source: https://msdn.microsoft.com/es-es/library/ch92fbc1(v=vs.110).aspx

Remove Time From Datetime in c# [duplicate]

This question already has answers here:
How to remove time portion of date in C# in DateTime object only?
(43 answers)
Closed 4 years ago.
I am using c#. I have a problem i am unable to remove the time format from datetime variable .
Here is my code.
string Date = ds.Tables[0].Rows[0]["serviceDate"].ToString();
string ServiceDate = string.Format("{0:MM/dd/yyyy}", Date);
How to remove the time from this format?
Call the Date property on your DateTime.
It gives you a DateTime with the same date, but with the time set to midnight.
By converting the Date into DateTime it will work fine.
DateTime date = Convert.ToDateTime(ds.Tables[0].Rows[0]["serviceDate"]);
string serviceDate = string.Format("{0:MM/dd/yyyy}", date);
Or if your serviceDate Field is already a Datetime then you can try this.
string ServiceDate = string.Format("{0:MM/dd/yyyy}", ds.Tables[0].Rows[0]["serviceDate"]);

Difference Between Dates Issue

I am having an issue of getting the difference in days between two dates. I will post my code below, but what I am trying to achieve is very simple, just get the difference between 2 dates in days and place the difference in a label.
Code:
string date1 = "";
string date2 = "";
if (myRdr.HasRows)
{
myRdr.Read();
date1 = myRdr["Date 1"].ToString();
date2 = myRdr["Date 2"].ToString();
}
Date 1 and Date 2 are what I am selecting from a query for SQL Server. The date format that I am pulling from my table is 12/25/2015
I have tried these lines to convert the string to date, but it returns nothing:
DateTime date1Diff= DateTime.ParseExact(date1, "dd/MM/yyyy", null);
DateTime date2Diff= DateTime.ParseExact(date2, "dd/MM/yyyy", null);
Then I was planning on getting the difference between date2Diff - date1Diff
So my question is, why are date1Diff and date2Diff returning nothing and what is the best way to get the difference between those two dates?
Put this method in class form or in the same form pass the string date format that you read it gives you date difference
public static double GetDateDiff(string d1, string d2)
{
double result = 0.0;
DateTime MyDate1 = Convert.ToDateTime(d1);
DateTime MyDate2 = Convert.ToDateTime(d2);
result = ((MyDate1 - MyDate2).TotalDays);
return result;
}

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 get today's date in mm/dd/yyyy format into a datetime variable in c#

I want today's date in mm/dd/yyyy format from a DateTime variable. How to get it?
I need to check this with some date variable so it must be also in date variable format?plz help
Ex: i need to get today date in mm/dd/yyyy format and i already date which is datetime datatype in mm/dd/yyyy format and i have to compare them
You should use DateTime.Today:
DateTime today = DateTime.Today; // As DateTime
string s_today = today.ToString("MM/dd/yyyy"); // As String
Edit: You edited your post to add another question, so here comes my edit to supply at least some sort of answer.
Update While you can use DateTime.Compare() you should use plain comparisson:
if(today < otherdate)
{
// Do something.
}
Alternatively, you can use DateTime-variables to check against other DateTime-variables using the DateTime.Compare() method. Both otpions will work and it comes down to preference and what you want to do with the result.
int result = DateTime.Compare(today, otherdate);
if(result < 0)
MessageBox.Show("Today is earlier than the 'otherdate'");
elseif(result > 0)
MessageBox.Show("Today is later than the 'other date'");
else
MessageBox.Show("Dates are equal...");
string datestring = DateTime.Now.ToString("MM/dd/yyyy");
MSDN say: Custom Date and Time Format Strings
To convert DateTime variable to string in the specified format:
DateTime d = ...;
string s = d.ToString("MM/dd/yyyy");
If you want to compare only date part of DateTime, not time part:
DateTime d1 = DateTime.Parse("10/10/2011");
DateTime d2 = DateTime.Parse("01/01/2011");
if (d1.Date > d2.Date)
{
// do the stuff
}
DateTime.Now.ToString("MM/dd/yyyy");
DateTime.Today.ToString("MM/dd/yyyy");
DateTime.Parse is what you are looking for...

Categories