Hi I am trying to convert a string to date time and then back to a string. This is my code.
try
{
string dt = "19/9/13";
DateTime.Parse(dt.ToString()).ToString("yyyy-MM-dd");
}
catch (Exception ex)
{
string msg = ex.Message;
}
and also tried Convert.ToDateTime(dt.ToString()).ToString("yyyy-MM-dd");
I am getting this error String was not recognized as a valid DateTime.. can any one give a solution.
I don't know what culture you are using, however, by default it's date-separator is used. So if you for example use . as separator that won't work.
Use CultureInfo.InvariantCulture and DateTime.ParseExact:
DateTime dt DateTime.ParseExact("19/9/13", "dd/M/yyyy", CultureInfo.InvariantCulture);
string result = dt.ToString("yyyy-MM-dd");
Here you have:
string time = "19/9/13";
DateTime resds =DateTime.ParseExact(time, "dd/M/yy", System.Globalization.CultureInfo.InvariantCulture);
string datet = resds.ToShortDateString();
DateTime.ParseExact documentation
Your parsing is true. The problem is the datetime because your computer supports another datetime format. It tries to get 19 as a month - and it throws this exception.
Probably if you write this it will work:
string dt = "9/19/13";
Or just change your computer settings to: dd/MMM/YYYY format.
try with DateTime.ParseExact :
DateTime.ParseExact(dt.ToString(), "dd/M/yy", null).ToString("yyyy-MM-dd");
You should use DateTime.ParseExact:
DateTime.ParseExact(dt, "dd/M/yy").ToString("yyyy-MM-dd");
And take a look at Custom Date and Time Format Strings.
Use Convert.ToDateTime() to convert string into date.. and then date to string use ToString()
string dt = "19/9/13";
Convert.ToDateTime(dt);
Related
I got a problem when trying to convert a date-time format with SAP RFC.
I'm trying this:
string tmpDate = argDate.ToString("dd.MM.yyyy");
DateTime date = Convert.ToDateTime(tmpDate);
IRfcFunction SAPRateAPI = null;
SAPRateAPI = _ecc.Repository.CreateFunction("ZRFC_CUST_CONDITION_RATE");
SAPRateAPI = CreateSAPRateAPI(SAPRateAPI, argPartnerSAPTranCode, argCustSAPTranCode, argMaterialCode, date);
SAPRateAPI.Invoke(_ecc);
But getting an error 'Specified Cast is not valid'
DateTime in C# has its own representation and doesn't has any "format" which you can see or change.
So phrase "datetime in dd.mm.yyyy format" has no sense at all.
Let's look at your code:
string tmpDate = argDate.ToString("dd.MM.yyyy");
DateTime date = Convert.ToDateTime(tmpDate);
Here you're converting DateTime to string and then back to DateTime.
You're getting exception on back cast just because Convert uses your windows specified culture, and in the case it differs from the one in the string - you need DateTime.ParseExact and explicit format specification.
But even if this cast will be successful - you again will get DateTime and this two lines will not change its format.
It looks like all you need - is just pass date only part of datetime as argument of your function. But it can be achieved pretty easily without any casts just by using argDate.Date (assuming agrDate is DateTime)
DateTime date = new DateTime( argDate.Years, argDate.Month, argDate.Day );
I think this is what you want.
See: C# Reference
Edit:
Which is the same as Andy Korneyev solution - Ok, his is nicer too look at, but both create a second DateTime object.
Consider using the DateTime.ParseExact method.
// Parse date and time with custom specifier.
string format = "dd.mm.yyyy hh:mm:tt";
DateTime date;
try {
date = DateTime.ParseExact(argDate, format, CultureInfo.InvariantCulture);
}
catch (FormatException e) {
throw new ArgumentException("argDate", e);
}
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);
I need to use
SqlDateTime.Parse(val)
where val is a string such as " 23.3.1992 00:00:00 ".
The string is in European format, that is, day precedes month. However Parse wants "American" format. How I can tell it to use particular datetime format / locale?
Thanks in advance!
Try this:
string val = "23.12.1992 00:00:00";
// Parse exactly from your input string to the native date format.
DateTime dt = DateTime.ParseExact(val, "dd.M.yyyy hh:mm:ss", null);
// Part to SqlDateTime then
System.Data.SqlTypes.SqlDateTime dtSql = System.Data.SqlTypes.SqlDateTime.Parse(dt.ToString("yyyy/MM/dd"));
This could be done in one statement, but just separated for illustration.
Have you tried DateTime instead of SQLDateTime
DateTime d = DateTime.Parse(val);
String s = d.ToString(CultureInfo.CreateSpecificCulture("en-US"));
Can you try this ?
string valInEuropean = "23.3.1992 00:00:00";
DateTime dateInEuropean = DateTime.Parse(valInEuropean);
string valInAmerican = dateInEuropean.ToString("yyyy-MM-dd HH:mm:ww");
For converting a string to datetime object when the format is known(in this case )
use
DateTime dwweek = DateTime.ParseExact("23.3.1992 00:00:00", "dd.MM.yyyy hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
The following case:
There is a string that has this format "2012-02-25 07:53:04"
But in the end, i rather want to end up with this format "25-02-2012 07:53:04"
I think i have 2 options. 1 would be to reformat the string and move it all around, but i dont think this is a clean way of doing this.
A other way that i was thinking about is to save the source string to a date parameter, and then write the date parameter back to a string in a certain date format.
But is this even possible to do ?
Do this:
DateTime.Parse("2012-02-25 07:53:04").ToString("dd-MM-yyyy hh:mm:ss");
Keep in mind this isn't culture-aware. And if you do need to store the intermediate result you could do that just as easily:
var myDate = DateTime.Parse("2012-02-25 07:53:04");
var myDateFormatted = myDate.ToString("dd-MM-yyyy hh:mm:ss");
Lastly, check out TryParse() if you can't guarantee the input format will always be valid.
Others have suggested using Parse - but I'd recommend using TryParseExact or ParseExact, also specifying the invariant culture unless you really want to use the current culture. For example:
string input = "2012-02-25 07:53:04";
DateTime dateTime;
if (!DateTime.TryParseExact(input, "yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dateTime))
{
Console.WriteLine("Couldn't parse value");
}
else
{
string formatted = dateTime.ToString("dd-MM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
Console.WriteLine("Formatted to: {0}", formatted);
}
Alternatively using Noda Time:
string input = "2012-02-25 07:53:04";
// These can be private static readonly fields. They're thread-safe
var inputPattern = LocalDateTimePattern.CreateWithInvariantInfo("yyyy-MM-dd HH:mm:ss");
var outputPattern = LocalDateTimePattern.CreateWithInvariantInfo("dd-MM-yy HH:mm:ss");
var parsed = inputPattern.Parse(input);
if (!parsed.Success)
{
Console.WriteLine("Couldn't parse value");
}
else
{
string formatted = outputPattern.Format(parsed.Value);
Console.WriteLine("Formatted to: {0}", formatted);
}
Parse as DateTime then reformat it. Be careful: use always an IFormatProvider!
Yes, it is quite possible. All you need to do is use DateTime.Parse to parse the string into a DateTime struct and then use ToString() to write the date back out to another string with the format you want.
You can parse this as a date object and then provide the formatting you want when using the date.ToString method:
date.ToString("dd-MM-yyyy hh:mm:ss");
Yes, you can use custom DateTime format strings to parse and reformat DateTime objects.
DateTime date = DateTime.ParseExact("2012-02-25 07:53:04", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
string formattedDated = date.ToString("dd-MM-yyyy HH:mm:ss");
i have a query string with format MM/DD/YYYY
I am using it in c# like
DateTime d = Request.QueryString["dateTime"].toString();
its giving me a lot of error saying the date time format is not recognized. If i manually change the datetime in browser address bar (query string) to dd/mm/yyyy then the program just works fine.
I cannot change the query string, is there a way in c# to get it from browser and then convert into date like dd/mm/yyyy please?
edit:
the query string:
http://localhost:49543/HM/Admin/ViewDetails.aspx?OrderNo=10&DateCreated=08/30/2010
so you can see the datecreated part is in MM/DD/YYYY format.
I am not able to grab it from c#. If I manually change that to 30/08/2010, it works
DateTime d = DateTime.ParseExact(Request.QueryString["dateTime"], "dd/MM/yyyy", CultureInfo.InvariantCulture);
How to turn string from request into DateTime:
DateTime d = DateTime.ParseExact(Request.QueryString["dateTime"], "dd/MM/yyyy", null);
DateTime.ParseExact is the solution you seek for.
But I recommend you to validate the querystring data with a function as follows:
bool isValidDate(string dtStr) {
string pattern = #"^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[2][0]\d{2})$)";
System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(pattern);
return re.IsMatch(dtStr);
}
EDIT 1: Besides ParseExact, you can use the following:
DateTime.Parse(dateString, new System.Globalization.CultureInfo("tr-TR"))
Turkish datetime format is dd/MM/YYYY.
// Parsing:
DateTime d = DateTime.Parse(Request.QueryString["dateTime"].toString());
// Conversion:
string dString = d.ToWhateverFormatYouWant();
And here's some info on formatting dates:
http://msdn.microsoft.com/en-us/library/az4se3k1(VS.71).aspx
DateTime.TryParse could be a great option..
Try this it should work
DateTime d =
DateTime.ParseExact(Request.QueryString["dateTime"],
"dd'/'MM'/'yyyy",
CultureInfo.InvariantCulture);
I faced something similar: DateTime Format in C#
You can use: DateTime.Now.ToString("dd/MM/yyyy");