I am trying to remove the time zone from a string.
The string looks like below.
2/05/2018 6:54:00 AM
This data has been retrieved from a local database.
Code Part:
string datCommisioned = (rdr.GetValue(4).ToString());
string dateonly = datCommisioned.ToString("dd/MM/yyyy");
When I tried to execute the above coding it's getting an error,
cannot convert from 'string' to 'System.IFormatProvider'
Any idea how to catch the date part excluding the time? Thanks!
Edit: This is probably not a duplicate question as I refer the other questions before posting. The context of this question is different because the string I'm extracting is not recognised as a valid DateTime (Manually entered by users) thus DateTime class cannot be used.
//Assuming value at index 4 is a DateTime.
string datCommisioned = rdr.GetDateTime(4).ToString(#"dd/MM/yyyy");
It's good practice to use the more specific and strongly typed methods with a DataReader. Helps identify bugs faster.
There are several approaches
Use DateTime object.
DateTime dateTime = DateTime.Parse(datCommissioned);
string dateonly = dateTime.ToString("dd/MM/yyyy");
Split on whitespace
var split = datCommissioned.Split(' ');
string dateonly = split[0];
You just need to change it to be this.
var datCommisioned = DateTime.parse(rdr.GetValue(4)).ToString("dd/MM/yyyy");
You are currently converting it to a string then trying to ToString() the String, when you just need to toString() the date from the reader.
Just another approach here; You can utilize DateTime.Parse() or perhaps a safer alternative, DateTime.TryParse(), to convert the string to a DateTime object. Then, use the Date property of the DateTime object to basically set the time to midnight, ie. 00:00:00. Depending on what you’re using the date for, having the DateTime object instead of a string could be helpful. You can then call ToString(“d”) or use another formatter to give you the date only portion in the desired format.
if (TryParse(datCommissioned, out DateTime commissionedDate))
{
commisionedDate = commisionedDate.Date;
string commissionedDateText = commissionedDate.ToString(“dd/MM/yyyy”);
}
Related
I have this confusion of converting 23/09/21 or 09/23/21 to a valid datetime
23/09/21 refers to development environment ,
09/23/21 refers to customer deploy environment
string _tmpCreatedDate = ((SAPbouiCOM.EditText)b1MatrixUser.Columns.Item("Col_8").Cells.Item(i + 1).Specific).Value;
hence becomes string _tmpCreatedDate = "23/09/21";
DateTime _swapCreatedDate = Convert.ToDateTime(_tmpCreatedDate);
above code will output string was not recognized as a valid DateTime.
tried _tmpCreatedDate = Convert.ChangeType(_tmpCreatedDate, typeof(DateTime)).ToString();
as well, same convert issue, as the input string is dynamic dd/MM/yy or
MM/dd/yy
how to handle this in correct way?
I think you can simply use DateTime.ParseExact
DateTime dt = DateTime.ParseExact(_tmpCreatedDate , "MM/dd/yyyy",CultureInfo.InvariantCulture);
Read more over here CultureInfo.InvariantCulture Property and DateTime.ParseExact
Added as comment, but to OP request, I am adding an answer:
You could specify date format in config in your application or detect in code, at app startup if it's development mode, then you can save appropriate format in some global variable.
One of ideas, if you're using dependency injection, would be to define some date provider service or even you could try specifying own IFormatProvider or something like that, and then using it in parsing methods of DateTime.
I am trying to extract date from date time field but in C# it is not helping me to do it without converting it to string.
This is my class:
public class Student_Info
{
public String Student_Name;
public DateTime DateofBirth;
}
Student_Info student = new Student_Info();
student.Student_Name = "XYZ";
student.DateofBirth = Convert.ToDateTime("2019-01-01");
MessageBox.Show(student.Student_Name + "" + student.DateofBirth);
This is how I am setting the value.
My expected result is XYZ 2019-01-01
But I am getting XYZ 1/1/2019 12:00:00 AM
Need Help?
Thanks in Advance
The DateTime struct always has a time component. There is a Date property that will mostly do what you asked, but even that has an implied time of midnight.
However, while the question text says this:
without converting it into string?
the code sample IS implicitly converting to a string:
MessageBox.Show(student.Student_Name + "" + student.DateofBirth);
In which case there are a number of options:
student.DateofBirth.ToShortDateString()
student.DateofBirth.ToString("d")
student.DateofBirth.ToString("d", CultureInfo.CreateSpecificCulture("de-DE")) //German format. You can put any culture here you need.
student.DateofBirth.ToString("d", CultureInfo.InvariantCulture)
student.DateofBrith.ToString("yyyy-MM-dd")
Just be careful here, because some of those rely on the operating system's date format, and users can configure that to do really weird stuff if they really want to.
You can also use any of these right in the MessageBox string:
MessageBox.Show($"{student.Student_Name}{student.DateofBirth:yyyy-MM-dd}");
MessageBox.Show(string.Format(CultureInfo.InvariantCulture, "{0}{1:d}", student.Student_Name, student.DateofBirth));
Finally, I get a little scared whenever I see someone wanting to create a date string resembling the ISO-8601 date format, as is the case here. There are plenty of legitimate reasons to do this. However, there is one common reason people want to do this that also happens to be very bad: SQL. If you're doing this so you can include it in an SQL command string, you're almost certainly doing something very wrong, and you need to take a step back and research parameterized queries before doing anything else.
Try this
MessageBox.Show(student.Student_Name + "" + student.DateofBirth.ToString("yyyy-MM-dd"));
I know this is a recurrent question but I cannot seem to be able to get this to work even after a lot of research! I want to convert a string to a DateTime.
public DateTime ConvertToDateTime(string thisDate)
{
return DateTime.ParseExact(thisDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);
}
(EDITED)
I give "2012-03-07" as a parameter and I get a DateTime that is 03/07/2012 12:00AM. When I wanted it to return: 2012-03-07 00:00:00
Your code is correct; your expectations are wrong.
When a method returns a DateTime, it has no format. Well, more accurately, it has a binary in-memory format that has no relation to its string format.
The debugger formats the DateTime to show it to you, but that has no bearing on the DateTime value itself. The format it uses is presumably determined by your locale settings.
When you want to display the DateTime to a user, or pass it as a string to some other function, you can format it as you like using one of the ToString overloads.
It may be that you are displaying or passing the return value of the function you've given; if so, the error is in the code displaying or passing the DateTime, not in the function you've given. If that's the case, edit your answer to include that code, and perhaps we can help you fix it.
Try this
public String ConvertToDateTime(string thisDate)
{
return DateTime.ParseExact(thisDate, "yyyy-MM-dd",
CultureInfo.InvariantCulture).toString("yyyy-MM-dd");
}
I am receiving some data into a variable of type object. In certain cases this data are date values. For that data, I would like to convert this to a string and return it in the same format as it was passed. In some cases, the object could be a datetime, in others a date only or time only values.
As soon as I convert the object to a date or a string, it is obviously given a time of midnight which in my scenario may be a valid time (so I cannot test to see if the time is midnight in which case I could deduce that it would have been a date only date value, nor can I use regex on it as there will always be a time element).
Intellisense shows me it correctly, ie in the format I am wishing to return the value.
Is there an easy way to achieve this (hopefully without using reflection)
Many thx
Simon
Your question is a little unclear but I think you're looking for something like this:
DateTime result;
if (DateTime.TryParse(value, out result))
{
// use result here
}
In the above code value is a string that represents the data coming in. The code will only enter the if block if the string is a valid DateTime. At which point you can do the processing you need on it.
Im not sure i understand the question but i would recommend you to take a look at this conversion example on MSDN, and see the Documentation of the DateTime Structur it contains a lot of Conversion/Formatting Methods i hope it helps.
There are many way to do formatting on the datetime and one of the simple way is fetch the data from the required table in the desired format. Like here you need to display the date and if you your format is dd/MM/yyyy then try this
select Convert(varchar(10),StartDate,103) as StartDateformat from table where filtername=#filtername
use this link to find other format Cast and Convert
From local variable to DateTime Conversion
DateTime todateformat = Convert.ToDateTime(txttodate.Text.Trim());
From DateTime to local variable Conversion in specific format
string startdate = todateformat.ToString("dd/MM/yyyy hh:mm:ss");
string Edate = collection["effectiveDatePicker"].ToString();
string Cdate = collection["cancelDatePicker"].ToString();
The Date I am getting is 20101112 or 20101116
Then I am doign soemthign like this to assing my Datetime variable
h.Edate= DateTime.ParseExact(collection["effectiveDatePicker"].ToString(), "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture, DateTimeStyles.NoCurrentDateDefault);
h.CDate= DateTime.ParseExact(collection["cancelDatePicker"].ToString(), "yyyyMMdd", System.Globalization.CultureInfo.CurrentCult
After saving to the data base.. I am seeing the EDate and CDate fileds somethign like this
11/10/2010
11/15/2010
with the same dates when I Submit again I am getting Error in the ParseExact bec the string I am getting is 11/10/2010 but its expecting 20101010
Can any body help me out?
You can specify the format that your dates are coming in as like this:
string Edate = collection["effectiveDatePicker"].ToString("yyyyMMdd");
string Cdate = collection["cancelDatePicker"].ToString("yyyyMMdd");
This should ensure that you are working with strings that look like what you want.
I can tell you for sure that there is a reformatting problem. I don't fully understand your code and the steps it takes (I guess you are using data binding or something similar).
The point seems that dates are initially set as yyyyMMdd, but when you postback the ToString() operator is applied to these dates, converting them to your OS's native format MM/dd/yyyy.
You must force them to be converted into yyyyMMdd again, because by default ToString will use CurrentUICulture which is not good for you.
You should show us the update code
I'm not sure what your specific question is. Because you're using DateTime.ParseExact() and are specifying a format of 'yyyyMMdd', passing in a string such as '11/04/2010' will fail.