convert string to date without time - c#

This line
System.DateTime.Parse("09/12/2009");
convert date (string) to 9/12/2009 12:00:00 AM. How can I get a date in the form 9/12/2009.
after explanations I do:
DateTime dt = System.DateTime.Parse(Request.Form["datepicker"]);
dt.ToString("dd/mm/yyyy");
/* and this code have time, why???*/

Your problem is not with the parsing but with the output. Look at how ToString works for DateTime, or use this example:
using System;
class Program
{
static void Main(string[] args)
{
DateTime dt = DateTime.Parse("09/12/2009");
Console.WriteLine(dt.ToString("dd/MM/yyyy"));
}
}
Or to get something in your locale:
Console.WriteLine(dt.ToShortDateString());
Update: Your update to the question implies that you do not understand fully my answer yet, so I'll add a little more explanation. There is no Date in .NET - there is only DateTime. If you want to represent a date in .NET, you do so by storing the time midnight at the start of that day. The time must always be stored, even if you don't need it. You cannot remove it. The important point is that when you display this DateTime to a user, you only show them the Date part.

Anything parsed to a DateTime object will contain date+time. If no time is sepcified, the assumed value will be 0000hr.
To get the date-only representation, it's up to how you format it to string.
E.g. theDate.ToString("dd/MM/yyyy")
Refer to the MSDN Date and Time Format Strings.

if you want to convert gridview datetime column to date only column use this code :
raddgvDaybook.Rows.ToList().ForEach(x =>
{
DateTime dt = DateTime.Parse(x.Cells["Vocdate"].Value.ToString());
string str = string.Format("{0:MM/dd/yyyy}", dt);
x.Cells["Vocdate"].Value = str;
});
I tested the code it will work if you bind the datetime as string in dgv.

Related

c# Is it possible to subtract a day in the datetime format

I have the following simple example:
string dt = DateTime.Now.ToString("yyyy-MM-dd hh.mm.ss");
I can't change the DateTime.Now, but I can change datetime format yyyy-MM-dd hh.mm.ss. Following this example the result must be today's date, but I need to get yesterday's date with the same parameters except day (year, month, hours, minutes and seconds). E.g. 2015-08-23 12.09.59 must be 2015-08-22 12.09.59. So is it possible to use some "-" operator or something else inside the datetime format to achieve the result?
If you want yesterday's date, you can do this
string dt = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd hh.mm.ss");
DateTime.AddDays() lets you add number of days, positive for future date, negative for past date.
E.g. 2015-08-23 12.09.59 must be 2015-08-22 12.09.59. So is it
possible to use some "-" operator or something else inside the
datetime format to achieve the result?
No, it's not possible inside the DateTime format. you can not change any thing. Because it is only for define format of the Date to display in string format. Any addition or subtraction can only be done before converting it to string format as suggested by "Arghya C".
Can you explain your limitation so we can solve your problem.
If you can only influence the date time pattern, than use the roundtrip format and parse the returning string back to a date time, add the calculation and format it into the desired format:
var dateTimeString = badLibrary.GetDateTime("o");
var dateTime = DateTime.Parse(dateTimeString, null, DateTimeStyles.RoundtripKind);
var newDateTime = dateTime.AddDays(-1);
return newDateTime.ToString("yyyy-MM-dd hh.mm.ss");

I need only date value part and time value part using ASP.NET C#

I have two parameters one for date and another for time, and i need date value part and time values part.
My two parameters are below.
// For Date parameter
DateTime dt = DateTime.ParseExact("01-jan-1999", "dd-MMM-yyyy", CultureInfo.InvariantCulture);
bo.Dateused5 = dt;
// For Time parameter
string Fromtiming = ddl_FromHours.SelectedItem.ToString() + ":" + ddl_FromMinutes.SelectedItem.ToString();
DateTime InterviewTime = Convert.ToDateTime(Fromtiming);//StartTime
bo.Dateused4 = InterviewTime;//InterviewTime
so i need to send mail to the candidate to only date part, should not contain time and time part, should not contain date.
are you looking for this:
DateTime dt = DateTime.ParseExact("01-jan-1999", "dd-MMM-yyyy", CultureInfo.InvariantCulture);
string mailDate = dt.ToString("dd-MMM-yyyy");// will give 01-jan-1999
string date = dt.ToString("dd-MM-yyyy"); // will give 01-01-1999
You can also try using String.Format()
string mailDate = String.Format("{0:dd-MM-yyyy}", dt); // will give 01-01-1999
You can use ToShortDateString():
DateTime dt = DateTime.ParseExact("01-jan-1999", "dd-MMM-yyyy", CultureInfo.InvariantCulture);
var date = dt.ToShortDateString();
Note that it uses date format attached to the current thread's culture info.
You would need to use strings rather than dates, so change the type of your variables to string so that
bo.Dateused5 = dt.ToString("dd-MMM-yyyy")
would set Dateused5 to a string of the date component, then
bo.Dateused4 = InterviewTime.ToString("HH:MM");
would set Dateused4 to the time component.
Couldn't test your code but I am very sure there are Functions "DateValue" and "TimeValue" you can make use of.
Something like,
Format(DateValue(any datetime), "dd-MM-yyyy")
gives you Only Date in the specified format. Similar way for TimeValue

Convert Timeformat to normal datetime

I have to convert this time format string (20130221191038.576375+330) to normal datetime through c# classes like datetime.
please share the idea to convert this..
Thanks guys, I got the solution for my requirement with the help of Erik,tung and BlackHatShadow.
Referred this
this also
The format you have is a CIM_DATETIME value, which is almost simple to parse. The only problem is that it specifies the timezone as an offset in number of minutes.
You can use the DateTime.TryParseExact to convert the portion of the string prior to the timezone specifier, then subtract the timezone value (in minutes) from the result to get the UTC datetime. Then you can convert to local time if you need, or leave it in UTC form.
public static DateTime? CIMToUTCDateTime(string CIM_DATETIME)
{
// CIM_DATETIME must be 25 characters in length
if (string.IsNullOrEmpty(CIM_DATETIME) || CIM_DATETIME.Length != 25)
return null;
// Get the datetime portion of the string without timezone offset
string dtPortion = CIM_DATETIME.Substring(0, 21);
// convert to datetime
DateTime dt;
if (!DateTime.TryParseExact(dtPortion, "yyyyMMddHHmmss.ffffff", System.Globalization.DateTimeFormatInfo.InvariantInfo, System.Globalization.DateTimeStyles.AssumeUniversal | System.Globalization.DateTimeStyles.AdjustToUniversal, out dt))
return null;
// subtract timezone offset to get UTC time equivalent
int tzoffset;
if (!Int32.TryParse(CIM_DATETIME.Substring(21), out tzoffset))
return null;
dt = dt.AddMinutes(-tzoffset);
// return UTC datetime
return dt;
}
And now that I've written this horrid little method, you've gone and found another solution. Typical :P
I know you already found a solution, but I came across this nice ManagementDateTimeConverter .Net class that does exactly what you want. All you need to do is:
// This gets converted to your local time
DateTime converted = ManagementDateTimeConverter.ToDateTime("20130221191038.576375+330")
// If you want the UTC equivalent:
converted.ToUniversalTime()

Trouble bringing in a string with d-MMM-yy format parse.exact to date but keeping date format and date type for sorting

As the title said I am bringing in a date string from a datatable with the format of "d-MMM-yy" or 27-AUG-06.
I need to convert it to a date type for sorting, but I need to keep the same format for display.
NOTE: I am using C#, .Net 2.0, and I am retyping this code so bear with me on typos
System.Globalization.DateTimeFormatInfo dtfi;
dtfi = new System.Globalization.DateTimeFormatInfo();
dtfi.ShortDatePattern = "d-MMM-yy";
dtfi.DateSeperator = "-";
//this is in a for loop with rowCnt being the row index/counter: loop and datatable is working fine.
//"newRow" represents a DataRow in the new table.
// the table [row] [column] is bringing in the string date like "27-AUG-06"
//colXDate IS RECORDED AS {8/27/2006 12:00:00 AM}
DateTime colXDate = DateTime.ParseExact(inputDataTable.Rows[rowCnt]["colX"].ToString(), "d-MMM-yy", System.Globalization.CultureInfo.InvariantCulture);
//#### THIS NEXT LINE IS WHERE IT GIVES ME AN ERROR "String was not recognized as valid datetime."
newRow["colX"] = Convert.ToDateTime(colXDate.ToString(), dtfi);
Since you already have colXDate as a DateTime, you don't need to convert it to a string and then back into a datetime.
Instead, try this:
newRow["colX"] = colXDate.ToString("d-MMM-yy");
Your line fails because ToString() will output the date in the format defined in the current culture and you are trying to convert it back to a date using your custom date format.
You need to set it to colXDate.ToString("d-MMM-yy").
SCENARIO: I am passing a datatable back as a DataGrids datasource. I am passing in a string field that is a date. I want to convert it to a date so that I can sort by it but I also want to maintain the same format that it was on the string that came in.
ISSUE: From some of my research it seems that the DateTime type is exactly that a datatype in whatever datatable that you put it in and is not formatable. So even though I bring in an unormal string date and convert it to a datetime via the DateTime.ParseExact, when I put it into my datetime field and try to format it (newRow["colX"] = colXDate.ToString("d-MMM-yy"); //as Scott had above) it still goes in as a set datetime format with hours...etc.
SOLUTION: So I resolved this by smoke and mirrors. I put 2 columns in the datatable, the first being the string format display date and the second the datetime type. On ItemDataBound I hid the datetime column (e.Item.Cells[5].Visible = false;) and then on the sort event I test for string date column (e.SortExpression == "colX") and if it is true I sort by the hidden datetime column.

Remove timestamp from date in C#?

I have a date like this: 2011-03-29 00:00:00.000
I want to remove the timestamp from that, is that possible?
Thanks :-)
Instance of DateTime class has ToShortDateString method that displays Date only
Maybe:
date.ToString("yyyy-MM-dd");
Probably the easiest way to do this is to use the parse function within the DateTime class which takes a string in the format you've described:
http://msdn.microsoft.com/en-us/library/1k1skd40%28v=VS.90%29.aspx
You can then use the 'Date' property within the class to get the date without the time stamp.
Hope this helps.
try
DateTime d ="2011-03-29 00:00:00';
string strDate = d.ToShortDateString();
Or
string strDate = d.ToString("dd/MM/yyyy");
There are a few ways to do this, however some depend on assumptions.
a) convert it date/time and then output just the date, the time is still there if you had wanted it
b) copy the string upto the first space
c) copy the first 11 characters (eg the date)
d) regex the output to confirm its a date/time format and then pull out the date
It depends a little I guess on what you want to do with it after and assuming it is a string in the first place. if not myDateTime.tostring('Y-M-D') would work.
DataColumn date = new DataColumn("date");
date.DataType = System.Type.GetType("System.String");
SomeDataTable.Columns.Add(date);
date.SetOrdinal(n); //placing it in the n+1th position
//n is where the actual column you want to replace is
foreach (DataRow dr in SomeDataTable.Rows)
{
DateTime date;
if (DateTime.TryParse(dr["date"].ToString(), out date))
{
dr["date"] = convert.ToDateTime(dr["date"]).ToString("MM/dd/yyyy");
}
}
SomeDataTable.Columns.RemoveAt(n-1);

Categories