Can't convert from String to Char - c#

I'm trying to Split this string: 2015-08-14 20:30:00
but the compiler shows this message:
Can't convert from String to Char
This is my code:
string date = reader["date"].ToString().Split("-").ToString();
The variable reader["date"] is an object, so I must convert it into a String. I want to Split the content into three other variable like this:
year: 2015
month: 08
day: 14
What am I doing wrong?

There is no String.Split overload that takes string as a parameter. That's why it looks closest overload which is char[] but there is no implicit conversation between them.
var array = "2015-08-14 20:30:00".Split(new char[]{'-', ' '});
will return
and you can get them with array[0], array[1] and array[2].
Also you can use to parse your string to DateTime instead (which your string is valid one) of splitting it like;
string s = "2015-08-14 20:30:00";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// dt.Year;
// dt.Month;
// dy.Day;
}
But since these properties are int, you will not get leading zeros for your single digit month and days.
In such a case, you can choose to use dd and MM custom date and time format specifiers.

Sometime a different approach should be considered. If your reader field datatype is date or datetime then using the correct datatype is the correct way to handle this info. A DateTime has already all you need.
DateTime dt = Convert.ToDateTime(reader["date"]);
int year = dt.Year;
int month = dt.Month;
int day = dt.Day;

As String.Split reaturns an array of strings you need date to be the same. So simply write
string[] date = Convert.ToString(reader["date"]).Split("-");

Related

Not getting correct date from DateTime in c#

I need only date in the yyyy-MM-dd format, but I'm getting (20/03/2018 0:00:00) date in wrong format.
var d = Convert.ToDateTime("2018-03-20T00:00:00.000",CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
var finaldate = DateTime.TryParseExact(d, "yyyy-MM-dd", null);
Output i am getting --20/03/2018 0:00:00
expected -- 2018-03-20
I will try to explain what the others meant when they wrote "DateTime has no format".
DateTime is a C# type that has properties for year, month, day, etc.
If you want to print a DateTime, you first have to convert it to a string. During this conversion, you can define the output format.
Also, if you parse a string into a DateTime, you can define the expected input format.
This is what the "Standard Date and Time Format Strings" / "Custom Date and Time Format Strings" are for.
An example:
string d = Convert.ToDateTime("2018-03-20T00:00:00.000",CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
DateTime finaldate = DateTime.TryParseExact(d, "yyyy-MM-dd", null); // not a string!
int year = finadate.Year; // year == 2018 (a number!)
int month = finaldate.Month; // month == 3 (a number again!)
string isoFormat = finaldate.ToString("yyyy-MM-dd"); // isoFormat == "2018-03-20"
string usFormat = finaldate.ToString("MM/dd/yyyy"); // usFormat == "03/20/2018"
// and so on...
Note that if you just call ToString() without specifying any format, the result will depend on the culture of the current thread (probably "en-Us" judging from the output you have shown). See DateTime.ToString Method.
DateTime always returns DateTime object with the time part.
To get expected output, you have to return string eg. DateTime.Now.ToString("dd-MM-yyyy")

convert string in a foreign language to date

I have these input:
27 februari 2014
14 maart 2013
7 november 2013
I would like to convert them all to date field as below:
27-02-2014
14-03-2013
17-11-2013
I have tried this method: DateTime enteredDate = DateTime.Parse(s); but it does not work, the error message was:
The string was not recognized as a valid DateTime. There is a unknown
word starting at index 3.
This appears as Dutch, you can parse it by passing new CultureInfo("nl-NL") to DateTime.ParseExact like:
string str = "27 februari 2014";
DateTime dt = DateTime.ParseExact(str, "d MMMM yyyy",
new System.Globalization.CultureInfoCultureInfo("nl-NL"));
Use single d which would consider both single and double digit day part.
To get the formatted output use:
string formattedDate = dt.ToString("dd-MM-yyyy", System.Globalization.CultureInfoCultureInfo.InvariantCulture);
DateTime allows you to provide a CultureInfo, which may be enough for you. If not, and you only get one foreign language, you could simply replace the the words by the correct English ones.

Date Convertion From String

I have a string "03/13/13" and when i convert this to DateTime it is throwing error as invalid string format.
How to convert string "03/13/13" to DateTime "03/13/13" (Same Format)
Convert.ToDateTime("03/13/13", new CultureInfo("en-GB"))
Use DateTime.ParseExact with format "M/d/yy"
DateTime dt = DateTime.ParseExact("03/13/13", "M/d/yy", CultureInfo.InvariantCulture);
Where in format:
M - For single digit or double digit month
d - For single digit or double digit day
yy- for two digits year.
You may see: Custom Date and Time Format Strings
Later if you want the string representation in the same format you can do:
string str = dt.ToString("MM/dd/yy")
You can use Convert.ToDateTime or DateTime.Parse ..
DateTime date = Convert.ToDateTime("5/17/2012");
or
DateTime date1 = DateTime.Parse("5/17/2012");
Example:
string date = "5/17/2012";
DateTime dates = Convert.ToDateTime(date);

Getting DateTime in a format with spaces between them not slashes if possible

I am trying to get date in this format
"yyyy MM dd"
with spaces between them not slashes, but its not working
using (SqlDataReader r = sqlComm.ExecuteReader())
{
if (r.Read())
{
DateTime Date
= Convert.ToDateTime((r["Date"]).ToString("yyyy/MM/dd"));
I can't make any change to SQL Stored Procedure at all
EDIT
Sorry it was giving me this for above "25 10 2012 10:00:00:00 AM" or something so I don;t think I was doing it properly, I only want date like this "yyyy MM dd"
how about changing \ into space?
.ToString("yyyy MM dd")
Building off of Marc's answer, it seems like you may be a bit confused about how the DateTime object vs. a string representation of the date actually work. The DateTime is just an offset from the starting point.
This line in your code first takes the value from the Date column in your SQL reader, then converts it to a string with the "yyyy/MM/DD" format, then finally turns that string into a DateTime object.
= Convert.ToDateTime((r["Date"]).ToString("yyyy/MM/dd"));
So as you can see, you're ending up with a DateTime object, not the display string you want. If you actually want this code to return just a formatted string , this is what your final line should look like:
EDIT
= r.GetDateTime(r.GetOrdinal("Date")).ToString("yyyy MM dd");
From date to string
var str= date.ToString("yyyy MM dd")
and for string to date
DateTime date = DateTime.ParseExact(string, "yyyy MM dd", CultureInfo.InvariantCulture);
So you want this format: "yyyy MM dd" but you use this "yyyy/MM/dd".
Instead:
String dateString = r.GetDateTime(r.GetOrdinal("Date")).ToString("yyyy MM dd");
look: http://ideone.com/XecnUP
A DateTime does not have a format. It is just the "how long since {epoch}", give-or-take some offset/timezone information. If the value in the source is a datetime, then all you need is:
DateTime date = (DateTime)r["Date"];
Then you might format that later at the UI. But to repeat: a DateTime does not have a format.

Split the date in c#

For Ex
You date enter in the various form in textbox
12/Augest/2010
augest/12/2010
2010/12/Augest
and out put is
three textbox First is day show= 12
textbox second is Months show= augest
textbox third is Year show= 2010
To parse/validate against three expected formats, you can use something like below. Given the pattern, once you know it is valid you could just use string.Split to get the first part; if you need something more elegant you could use TryParseExact for each pattern in turn and extract the desired portion (or re-format it).
string s1 = "12/August/2010",
s2 = "August/12/2010",
s3 = "2010/12/August";
string[] formats = { "dd/MMMM/yyyy", "MMMM/dd/yyyy", "yyyy/dd/MMMM" };
DateTime d1 = DateTime.ParseExact(s1, formats,
CultureInfo.CurrentCulture, DateTimeStyles.None),
d2 = DateTime.ParseExact(s2, formats,
CultureInfo.CurrentCulture, DateTimeStyles.None),
d3 = DateTime.ParseExact(s3, formats,
CultureInfo.CurrentCulture, DateTimeStyles.None);
Use DateTime.Parse(String, IFormatProvider) or DateTime.ParseExact to convert the string into DateTime.
Then you can extract the day, month and year using the corresponding properties.
Use DateTime.Parse(s). See MSDN
Then you can get the individual parts of a DateTime structure.
e.g.
DateTime date = DateTime.Parse("some input date string");
string day = DateTime.Day.ToString();
string month = DateTime.Month.ToString();
string year = DateTime.Year.ToString();
date dt date.Parse(txtBox.text);
txtBox1.Text = dt.Day.ToString();
txtBox2.Text = dt.ToString("MMM");
txtBox3.Text = dt.Year.ToString();
date.Parse might throw depending on the string you give it, but then you can fall back by trying to parse it using a different culture.
Edit: Added an M

Categories