Converting string to date time by parsing - c#

I am getting a string in the following format
string dt= "\"2014-06-01T05:00:00.000Z\""
I am trying to convert it to Date following way
mDateTime dt = Convert.ToDateTime(dt)
I get error saying When converting string to date time use parse the string.
Please let me know how I can parse the string to date. Thanks

Convert.ToDateTime method fails because this is not a standard date and time pattern for your CurrentCulture (And probably no culture support this format).
You can use custom date and time formatting with DateTime.TryParseExact or DateTime.ParseExact methods.
Here an example on LINQPad;
string s = "\"2014-06-01T05:00:00.000Z\"";
DateTime dt;
if(DateTime.TryParseExact(s, "'\"'yyyy-MM-dd'T'HH:mm:ss.fff'Z\"'",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
dt.Dump();
}
Output will be;
6/1/2014 5:00:00 AM
Here a demonstration.

At first you have to trim quotes, then parse:
DateTime result = DateTime.Parse(dt.Trim('\"'));

you can use below menioned code
string dt = "\"2014-06-01T05:00:00.000Z\"";
dt = dt.Replace("\"", "");
DateTime dt12 = Convert.ToDateTime(dt);

Try This:
string dt = "\"2014-06-01T05:00:00.000Z\"";
dt = dt.Replace("\"", "");
DateTime dtFinal = DateTime.ParseExact(dt,"yyyy-MM-ddTHH:mm:ss.fffZ",
CultureInfo.InvariantCulture);

Related

Error when converting date to dd-MMM-yy

I am getting an error when I run the following line of code:
DateTime dt = DateTime.ParseExact(bolShipdate, "dd/MMM/yyyy", null);
The error is:
String was not recognized as a valid DateTime.
The bolShipdate value is 02-21-2016. I need to convert the date to 21-Feb-16.
How can I resolve this?
Your format in ParseExact needs to match your string. dd/MMM/yyyy doesn't match the sample data provided. try:
var bolShipdate = "02-21-2016";
DateTime dt = DateTime.ParseExact(bolShipdate, "MM-dd-yyyy", null);
Console.WriteLine(dt.ToString("dd-MMM-yy")); // Dispays 21-Feb-16
(Example fiddle)
Declaration of DateTime.ParseExact is
public static DateTime ParseExact(
string s,
string format,
IFormatProvider provider
)
Here you will want to pass the format you are parsing not the expected result. And it looks like your string is of the format MM-dd-yyyy.
You can then use .ToString(string format to get the date in your desired format:
string date = "02-21-2016";
DateTime dt = DateTime.ParseExact(date, "MM-dd-yyyy", CultureInfo.InvariantCulture);
string newFormat = dt.ToString("dd-MMM-yy");
Console.WriteLine(newFormat);
Hope this can resolve:
var date = "02-21-2016";
DateTime dt = DateTime.ParseExact(date, "MM-dd-yyyy", CultureInfo.InvariantCulture);
string result = dt.ToString("dd-MMM-yy");

Convert String to Date time C# Error String was not recognize

I am trying to convert string to date time. My textbox contains a date only. My code is:
if (!String.IsNullOrEmpty(this.txtEOIDate.Text))
{
DateTime dt;
dt = DateTime.ParseExact(txtEOIDate.ToString(), "yyyy-MM-dd HH:mm tt",null);
invProject.created = dt;
}
txtEOIDate.Text contains "8/22/2014"
"invproject" is class object have datetime field "created"
error is String was not recognized as a valid DateTime.
on line
dt = DateTime.ParseExact(txtEOIDate.ToString(), "yyyy-MM-dd HH:mm tt",null);
I am using framework 4.0
UPDATE ANSWER:
Solution which work for me is:
string tes = txtEOIDate.Text.ToString().Trim();
DateTime dt = new DateTime(Convert.ToInt16(tes.Split('/')[2]), Convert.ToInt16(tes.Split('/')[0]), Convert.ToInt16( tes.Split('/')[1]));
invProject.created = dt;
Change this:
dt = DateTime.ParseExact(txtEOIDate.ToString(), "yyyy-MM-dd HH:mm tt",null);
To this:
dt = DateTime.ParseExact(txtEOIDate.Text, "yyyy-MM-dd HH:mm tt",null);
If you are using the standard textbox then txtEOIDate.ToString() is equals to:
System.Web.UI.WebControls.TextBox
Not:
8/22/2014
Update
If you want to parse a date which is in the format M/dd/yyyy. Why not just put it in the ParseExact. Like this:
DateTime.ParseExact(txtEOIDate.Text,"M/dd/yyyy",CultureInfo.InvariantCulture);
Why do you need ParseExact?
You cannot use ParseExact since you are not submitting all the values (hours, minutes etc.) I would do like this:
var dt = DateTime.Parse(txtEOIDate.Text);
UPDATE
This works:
if (!String.IsNullOrEmpty(this.txtEOIDate.Text))
{
var dt = DateTime.Parse(this.txtEOIDate.Text);
invProject.created = dt;
}
Firstly, ensure you are actually using txtEOIDate.Text, not txtEOIDate.ToString(). Secondly, I personally would use TryParse like this:
DateTime MyNewDT;
DateTime.TryParseExact(txtEOIDate.Text, "MM/dd/yyyy", null, System.Globalization.DateTimeStyles.None, out MyNewDT);
The format you input is not what you want it to be in but what format the string is currently in. As such, you are creating a DateTime variable that you can use.
txtEOIDate.ToString() does not return the Text of txtEOIDate
you should to change it to txtEOIDate.Text ...
and
change FormatString from yyyy-MM-dd HH:mm tt to M/dd/yyyy

How to convert any date format to yyyy-MM-dd

My app parses a string data, extracts the date and identify the format of the date and convert it to yyyy-MM-dd.
The source date could be anything lime dd-mm-yyyy, dd/mm/yyyy, mm-dd-yyyy, mm/dd/yyyy or even yyyy-MM-dd.
Other than attempting different permutations and combinations using switch case, is there any other efficient way to do it?
string sourceDate = "31-08-2012";
String.Format("{0:yyyy-MM-dd}", sourceDate);
The above code simply returns the same sourceDate "31-08-2012".
string DateString = "11/12/2009";
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dateVal = DateTime.ParseExact(DateString, "yyyy-MM-dd", culture);
These Links might also Help you
DateTime.ToString() Patterns
String Format for DateTime [C#]
Convert your string to DateTime and then use DateTime.ToString("yyyy-MM-dd");
DateTime temp = DateTime.ParseExact(sourceDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
string str = temp.ToString("yyyy-MM-dd");
string sourceDateText = "31-08-2012";
DateTime sourceDate = DateTime.Parse(sourceDateText, "dd-MM-yyyy")
string formatted = sourceDate.ToString("yyyy-MM-dd");
You can write your possible date formats in array and parse date as following:
public static void Main(string[] args)
{
string dd = "12/31/2015"; //or 31/12/2015
DateTime startDate;
string[] formats = { "dd/MM/yyyy", "dd/M/yyyy", "d/M/yyyy", "d/MM/yyyy",
"dd/MM/yy", "dd/M/yy", "d/M/yy", "d/MM/yy", "MM/dd/yyyy"};
DateTime.TryParseExact(dd, formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out startDate);
Console.WriteLine(startDate.ToString("yyyy-MM-dd"));
}
You can change your Date Format From dd/MM/yyyy to yyyy-MM-dd in following way:
string date = DateTime.ParseExact(SourceDate, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
Here, SourceDate is variable in which you will get selected date.
You will need to parse the input to a DateTime object and then convert it to any text format you want.
If you are not sure what format you will get, you can restrict the user to a fixed format by using validation or datetimePicker, or some other component.
This is your primary problem:
The source date could be anything like dd-mm-yyyy, dd/mm/yyyy,
mm-dd-yyyy, mm/dd/yyyy or even yyyy-MM-dd.
If you're given 01/02/2013, is it Jan 2 or Feb 1? You should solve this problem first and parsing the input will be much easier.
I suggest you take a step back and explore what you are trying to solve in more detail.
Try this code:
lblUDate.Text = DateTime.Parse(ds.Tables[0].Rows[0]["AppMstRealPaidTime"].ToString()).ToString("yyyy-MM-dd");
if (DateTime.TryParse(datetoparser, out dateValue))
{
string formatedDate = dateValue.ToString("yyyy-MM-dd");
}
string sourceDate = "15/06/2021T00.00.00";
DateTime Date = DateTime.Parse(sourceDate)
string date = Date.ToString("yyyy-MM-dd");
Convert.toDateTime(sourceDate).toString("yyyy-MM-dd");
Convert.ToDateTime((string)item["LeaveFromDate"]).ToString("dd/MM/yyyy")
This might be helpful

Can any one tell what's wrong in my conversion from string to Date time

I write the following code to convert a string to Date time but i am getting an exception so can any one help me
string str = "2/30/2011";
DateTime dt = DateTime.ParseExact(str, "yyMMdd", CultureInfo.InvariantCulture);`
Other than the non-existing date? February 30th is not a date unless you're using MySQL...
Oh, and of course, your format is wrong. It should be M/dd//yyyy (because that's how your string is formatted).
try
DateTime dt = DateTime.ParseExact(str, "MM/dd/yyyy", CultureInfo.InvariantCulture);
You have to do it like this:
string str = "2/30/2011";
DateTime dt = DateTime.ParseExact(str, "M/dd/yyyy", CultureInfo.InvariantCulture);`
Morover, you're using a format yyMMdd whereas your date is expressed in M/dd/yy

Parse C# string to DateTime

I have a string like this:
250920111414
I want to create a DateTime object from that string. As of now, I use substring and do it like this:
string date = 250920111414;
int year = Convert.ToInt32(date.Substring(4, 4));
int month = Convert.ToInt32(date.Substring(2, 2));
...
DateTime dt = new DateTime(year, month, day ...);
Is it possible to use string format, to do the same, without substring?
Absolutely. Guessing the format from your string, you can use ParseExact
string format = "ddMMyyyyHHmm";
DateTime dt = DateTime.ParseExact(value, format, CultureInfo.InvariantCulture);
or TryParseExact:
DateTime dt;
bool success = DateTime.TryParseExact(value, format,
CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
The latter call will simply return false on parse failure, instead of throwing an exception - if you may have bad data which shouldn't cause the overall task to fail (e.g. it's user input, and you just want to prompt them) then this is a better call to use.
EDIT: For more details about the format string details, see "Custom Date and Time Format Strings" in MSDN.
You could use:
DateTime dt = DateTime.ParseExact(
date,
"ddMMyyyyHHmm",
CultureInfo.InvariantCulture);
string iDate = "05/05/2005";
DateTime oDate = Convert.ToDateTime(iDate);
DateTime oDate = DateTime.ParseExact(iString, "yyyy-MM-dd HH:mm tt",null);
DateTime Formats

Categories

Resources