Error while converting string to DateTime after publishing to web server - c#

I am using below code
DateTime dtt=new DateTime();
dtt = Convert.ToDateTime(FromDate);
// DateTime dtt = DateTime.Parse(FromDate); //this also gives the same error
con = new MySqlConnection(conString);
con.Open();
for (int i = 1; i <= TotalDays; i++)
{
string updateHotelBooking = "Update tbl_hotelbookingdetail set `BookedRoom`=`BookedRoom`+"+1+", `AvailableRoom`=`TotalRoom`-`BookedRoom` where `HotelID`="+HotelID+" AND `CurrentDate`='"+dtt.ToString("dd-MM-yyyy")+"'";
MySqlCommand cmd7=new MySqlCommand(updateHotelBooking,con);
cmd7.ExecuteNonQuery();
dtt = dtt.AddDays(1);
}
This code is in one of my webservice which I am using for iPhone application.
here FromDate is string with value in this formate 15-11-2011 which is coming from the application in string format. I am converting it to DateTime because in loop of total days
I need to add day to dtt.
It is working fine on local host with dtt value 15-11-2011 00:00:00
but when I published it,it gives error
String was not recognize as valid DateTime

This is almost certainly because your server uses a different culture by default - and your code is just using the current thread culture.
You can specify this using DateTime.Parse - or specify the pattern explicitly with DateTime.ParseExact or DateTime.TryParseExact - but we need to know more about where the string is coming from to suggest the best approach. Is it from the user? If so, you should use the user's culture to parse it. Is it a specific format (e.g. from an XML document) instead? If so, parse using that specific format.
Ideally, get rid of the string part entirely - if you're fetching it from a database for example, can you store it and fetch it as a DateTime instead of as a string? It's worth trying to reduce the number of string conversions involved as far as possible.
EDIT: To parse from a fixed format of dd-MM-yyyy I would use:
DateTime value;
if (DateTime.TryParseExact(text, "dd-MM-yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal,
out value))
{
// Value will now be midnight UTC on the given date
}
else
{
// Parsing failed - invalid data
}

What are you culture settings on your local machine and on the server?
The DateTime conversion is dependent on the current culture - dates are written quite differently in different countries.
One way to make the conversion "predictible" is to use the invariant culture:
DateTime dtt = Convert.ToDateTime(FromDate, CultureInfo.InvariantCulture);

the server date format may be in mm/dd/yyyy and you are trying to pass dd/mm/yyyy
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string[] dateValues = { "30-12-2011", "12-30-2011",
"30-12-11", "12-30-11" };
string pattern = "MM-dd-yy";
DateTime parsedDate;
foreach (var dateValue in dateValues) {
if (DateTime.TryParseExact(dateValue, pattern, null,
DateTimeStyles.None, out parsedDate))
Console.WriteLine("Converted '{0}' to {1:d}.",
dateValue, parsedDate);
else
Console.WriteLine("Unable to convert '{0}' to a date and time.",
dateValue);
}
}
}
// The example displays the following output:
// Unable to convert '30-12-2011' to a date and time.
// Unable to convert '12-30-2011' to a date and time.
// Unable to convert '30-12-11' to a date and time.
// Converted '12-30-11' to 12/30/2011.
Check this for more details

Log (or otherwise provide feedback to yourself) what FromDate is. Maybe it's empty?

May the Language Settings on the Server are different so it does not recognize the dd-MM-yyyy - try using DateTime.ParseExact(dateString, "dd-MM-yyyy", CultureInfo.InvariantCulture);

Related

DateTime conversion from UI

I have a form where the user selects the Date from the UI .
I am getting the following value from UI
var uiDate = "2019-05-03T00:00:00.000Z".
I need to convert this to DateTime for further processing .
var dt = Convert.ToDateTime(uiDate);
The value of dt is "5/2/2019 8:00:00PM" .
As we can see I am always getting one day back after DateTime conversion from the date selected from UI. I was expecting "5/3/2019".
I am not able to figure out why is this happening after DateTime conversion?
Convert.ToDateTime is implicitly converting the value to local time. If you use DateTime.ParseExact, you can specify appropriate conversion options:
using System;
using System.Globalization;
class Program
{
static void Main()
{
string text = "2019-05-03T00:00:00.000Z";
DateTime parsed = DateTime.ParseExact(
text, // The value to parse
// The pattern to use for parsing
"yyyy-MM-dd'T'HH:mm:ss.FFF'Z'",
// Use the invariant culture for parsing
CultureInfo.InvariantCulture,
// Assume it's already in UTC, and keep it that way
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
Console.WriteLine(parsed); // 03/05/2019 00:00:00 (on my machine; format will vary)
Console.WriteLine(parsed.Kind); // Utc
}
}

Convert 2015-06-01T02:31:00+0000 to DateTime object c#

I'm writting an app that consume this webservice:
http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json
as you can see there, the JSON object comes with an utc datetime field. I want to save this information in a simple DateTime object with the following format "yyyy-MM-dd HH:mm:ss".
This is my code:
DateTime dateParsed = DateTime.Now;
DateTime.TryParseExact((string)resource.SelectToken("resource").SelectToken("fields")["utctime"], "yyyy'-'MM'-'dd'T'HH':'mm':'ssz", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal, out dateParsed);
I'm getting an DateTime object initialized in the year 0001.
What I'm doing wrong?
You should be using the K custom format specifier (instead of z).
string s = "2015-06-01T04:41:10+0000";
DateTime dt = DateTime.ParseExact(s, "yyyy-MM-dd'T'HH:mm:ssK",
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal);
It will read the +0000 as the offset. Then by using the AdjustToUniversal style, the resulting DateTime will also be in terms of Universal time, having DateTimeKind.Utc.
Also, since you're reading from a known data source, there's no real benefit of using TryParseExact. The format from your data source is fixed, so just use ParseExact with that format. The Try... methods are primarily for validating user input, or when the source format could vary.
One last point - if you just parse your data using JSON.net, that format should automatically be recognized. You just use a DateTime or DateTimeOffset property, and it would parse it without issue.
You have just an error in your Format-String. This is a working sample:
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
DateTime dateParsed = DateTime.Now;
if ( DateTime.TryParseExact( "2015-06-01T02:31:00+0000", "yyyy-MM-ddThh:mm:ss+0000", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal, out dateParsed ) ) {
Console.WriteLine(string.Format("Parsing done: {0:MM/dd/yyyy # hh:mm}", dateParsed ) );
} else {
Console.WriteLine("No result");
}
}
}
Note: the +0000 is hardcoded, when you get other values you would need to detect them. If the api returns only +0 values, you could cut them off and work without z.

Converting datetime format without using SAP RFC with C#

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);
}

Storing date time in culture neutral format + C#

I accept date info from the user, via date picker. I need to store them in a culture neutral way. The problem I am facing is, if I store the date as per en-US format (based on calendar settings), namely 11/20/1990 it will fail to parse when the culture is en-GB.
And vice versa happens when culture is en-US, date stored as per UK format, dd/mm/yyyy refuses to parse. How do I store date info in a culture neutral way in a file so that, I get the date to work in both locations?
DateTime.TryParse(userEnteredValue, out result);
result.ToShortDateString(); //this is what I am doing
tried this code for invariant culture
string input = "20/10/1983";
DateTime userInput;
bool result = DateTime.TryParse(input, out userInput);
string invariantCulture = userInput.Date.ToString(CultureInfo.InvariantCulture);
DateTime storedValue;
result = DateTime.TryParse(invariantCulture, out storedValue);
tried this code with en-GB calendar settings, second statement DateTime.TryParse fails infact.
#Soner Gönül's answer is spot on if you are saving the dates to a database. However, you mention that you are looking to round-trip a DateTime to and from a file.
As the file is presumably a text file you'll need to write the DateTime in a culture neutral manner. You can do this by using the "O" format specified on the DateTime.ToString method. This will output a string representation that complies with ISO 8601. The resultant string can be parsed using DateTime.Parse without the need for culture information.
As an example:
string filename = #"c:\temp\test.txt";
string usDateString = "11/18/2014 12:32"; // MM/dd/yyyy
string ukDateString = "18/11/2014 12:33"; // dd/MM/yyyy
//I'm mimicking you getting the DateTime from the user here
//I'm assuming when you receive the date(s) from the front
//end you'll know the culture - if not then all bets are off.
DateTime usDate =
DateTime.Parse(usDateString, CultureInfo.GetCultureInfo("en-US"));
DateTime ukDate =
DateTime.Parse(ukDateString, CultureInfo.GetCultureInfo("en-GB"));
//write the dates to a file using the "o" specifier
File.AppendAllText(filename, usDate.ToString("o") + Environment.NewLine);
File.AppendAllText(filename, ukDate.ToString("o") + Environment.NewLine);
//read them back in as strings
string[] contents = File.ReadAllLines(filename);
foreach (var date in contents)
{
//prove we can parse them as dates.
Console.WriteLine(DateTime.Parse(date).ToString());
}
This creates a file with the contents:
2014-11-18T12:32:00.0000000
2014-11-18T12:33:00.0000000
and on my system (in the UK) it prints:
18/11/2014 12:32:00
18/11/2014 12:33:00
if I store the date as per en-US format...
Please stop! Looks like you try to save your DateTime values with their string representations.
A DateTime doesn't have any implicit format. It has just date and time values. String representations of them can have a format. Generate your insert queries and pass your DateTime values directly with parameterized way.
Please read;
Bad habits to kick : choosing the wrong data type
If you want to get string representations of your DateTime values with specific format, you can always use DateTime.ToString() method and it's overloads.
Your en-GB culture can parse MM.dd.yyyy (since you use / format specifier which replaces itself supplied culture DateSeparator) and en-US culture can parse MM/dd/yyyy as well.
But since you use .ToShortDateString() method, this represents your datetime based your CurrentCulture settings. As a solution, you can set this property which culture you want and ToShortDateString works based on it.
result = DateTime.TryParse(invariantCulture, out storedValue);
tried this code with en-UK calendar settings, second statement
DateTime.TryParse fails infact.
Because this DateTime.TryParse uses your CurrentCulture and since your invariantCulture variable is 10/20/1983 00:00:00, that means this is not a standard date and time format for your CurrentCulture.
There is no such a culture as en-UK by the way.
10/20/1983 00:00:00 is MM/dd/yyyy HH:mm:ss format. But en-GB culture doesn't have this format as a standard date and time format, that's why your method returns false.
As an alternative, you can use custom format strings like;
string s = "10/20/1983 00:00:00";
string format = "MM/dd/yyyy HH:mm:ss";
DateTime dt;
if (DateTime.TryParseExact(s, format, CultureInfo.GetCultureInfo("en-GB"),
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
I bumped into this question and figured I'd bring in some other way nobody has mentioned yet:
DateTime.ToBinary() for serializing and DateTime.FromBinary(Int64) for deserialization.
What these do is the following:
ToBinary() returns a long which can be easily stored in a culture invariant way.
FromBinary(Int64) will return a DateTime object from the long parameter supplied.
(They even take the date time Kind property into consideration).
And here's some code to go with it:
DateTime d1l = DateTime.Now;
long dl = d1l.ToBinary();
DateTime d2l = DateTime.FromBinary(dl);
DateTime d1u = DateTime.UtcNow;
long du = d1u.ToBinary();
DateTime d2u = DateTime.FromBinary(du);
Console.WriteLine("Local test passed: " + (d1l == d2l).ToString());
Console.WriteLine("d2l kind: " + d2l.Kind.ToString());
Console.WriteLine("Utc test passed: " + (d1u == d2u).ToString());
Console.WriteLine("d2u kind: " + d2u.Kind.ToString());
And the console output:
Local test passed: True
d2l kind: Local
Utc test passed: True
d2u kind: Utc
I find this to be pretty neat!
String s = "24. 11. 2001";
d = DateTime.Parse(s, CultureInfo.CreateSpecificCulture("sk-SK"));
en-AU (English Austrailia): 24/11/2001
en-IA (English India): 24-11-2001
en-ZA (English South Africa): 2001/11/24
en-US (English United States): 11/24/2001
i suspect you prefer English (India) (en-IA).
But if you really can't decide what culture to use when converting dates to strings and vice-versa, and the dates are never meant to be shown to a user, then you can use the Invariant Culture:
String s = "11/24/2001" //invariant culture formatted date
d = DateTime.Parse(s, CultureInfo.InvariantCulture); //parse invariant culture date
s = d.ToString(CultureInfo.InvariantCulture); //convert to invariant culture string
I tried to figure out a solution via this approach, please let me know if its correct.
The code which I use is below.
For Saving date time I use ticks as below.
DateTime userInput;
bool result = DateTime.TryParse(this.dpSave.Text, out userInput);
if (result)
{
long ticks = userInput.Ticks;
System.IO.File.WriteAllText(#"D:\folder\Ticks.txt", ticks.ToString());
}
else
{
MessageBox.Show("Date time parse failed");
}
For loading it back, I use
if (System.IO.File.Exists(#"D:\folder\Ticks.txt"))
{
string contents = System.IO.File.ReadAllText(#"D:\Sandeep\Ticks.txt");
long ticks;
if (long.TryParse(contents, out ticks))
{
DateTime storedDateTime = new DateTime(ticks);
MessageBox.Show("Stored Date" + storedDateTime.ToShortDateString());
}
else
{
MessageBox.Show("Unable to obtain stored dates");
}
}
this seems to work, provided, I save using en-US culture and load using en-GB culture.
please let me know if this is the right approach!
a) Exchange data shall always be stored culture invariant (xml etc)
b)You've gotta to be careful with the terminology.
What you exactly mean is culture INVARIANT (and not 'culture neutral').
There are three types of cultures:
1) invariant
2) culture neutral (e.g. "en")
3) culture specific (e.g "en-US")
public DateTime getdate3()
{
CultureInfo Invc = CultureInfo.InvariantCulture; //culture
string cul = Thread.CurrentThread.CurrentCulture.Name;
CultureInfo us = new CultureInfo(cul);
string shortUsDateFormatString = us.DateTimeFormat.ShortDatePattern;//pattern
DateTime dt = Convert.ToDateTime(DateTime.Now);
TimeZoneInfo myZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"); //india zone
DateTime dateindia = TimeZoneInfo.ConvertTime(dt, myZone);
string dt1 = Convert.ToDateTime(dateindia).ToString(shortUsDateFormatString); //string format
}

String was not recognized as a valid DateTime " format dd/MM/yyyy"

I am trying to convert my string formatted value to date type with format dd/MM/yyyy.
this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
What is the problem ?
It has a second override which asks for IFormatProvider. What is this? Do I need to pass this also? If Yes how to use it for this case?
Edit
What are the differences between Parse and ParseExact?
Edit 2
Both answers of Slaks and Sam are working for me, currently user is giving the input but this will be assured by me that they are valid by using maskTextbox.
Which answer is better considering all aspects like type saftey, performance or something you feel like
Use DateTime.ParseExact.
this.Text="22/11/2009";
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);
You need to call ParseExact, which parses a date that exactly matches a format that you supply.
For example:
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
The IFormatProvider parameter specifies the culture to use to parse the date.
Unless your string comes from the user, you should pass CultureInfo.InvariantCulture.
If the string does come from the user, you should pass CultureInfo.CurrentCulture, which will use the settings that the user specified in Regional Options in Control Panel.
Parsing a string representation of a DateTime is a tricky thing because different cultures have different date formats. .Net is aware of these date formats and pulls them from your current culture (System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat) when you call DateTime.Parse(this.Text);
For example, the string "22/11/2009" does not match the ShortDatePattern for the United States (en-US) but it does match for France (fr-FR).
Now, you can either call DateTime.ParseExact and pass in the exact format string that you're expecting, or you can pass in an appropriate culture to DateTime.Parse to parse the date.
For example, this will parse your date correctly:
DateTime.Parse( "22/11/2009", CultureInfo.CreateSpecificCulture("fr-FR") );
Of course, you shouldn't just randomly pick France, but something appropriate to your needs.
What you need to figure out is what System.Threading.Thread.CurrentThread.CurrentCulture is set to, and if/why it differs from what you expect.
Although the above solutions are effective, you can also modify the webconfig file with the following...
<configuration>
<system.web>
<globalization culture="en-GB"/>
</system.web>
</configuration>
Ref : Datetime format different on local machine compared to production machine
You might need to specify the culture for that specific date format as in:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); //dd/MM/yyyy
this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
For more details go here:
http://msdn.microsoft.com/en-us/library/5hh873ya.aspx
Based on this reference, the next approach worked for me:
// e.g. format = "dd/MM/yyyy", dateString = "10/07/2017"
var formatInfo = new DateTimeFormatInfo()
{
ShortDatePattern = format
};
date = Convert.ToDateTime(dateString, formatInfo);
After spending lot of time I have solved the problem
string strDate = PreocessDate(data);
string[] dateString = strDate.Split('/');
DateTime enter_date = Convert.ToDateTime(dateString[1]+"/"+dateString[0]+"/"+dateString[2]);
private DateTime ConvertToDateTime(string strDateTime)
{
DateTime dtFinaldate; string sDateTime;
try { dtFinaldate = Convert.ToDateTime(strDateTime); }
catch (Exception e)
{
string[] sDate = strDateTime.Split('/');
sDateTime = sDate[1] + '/' + sDate[0] + '/' + sDate[2];
dtFinaldate = Convert.ToDateTime(sDateTime);
}
return dtFinaldate;
}
use this to convert string to datetime:
Datetime DT = DateTime.ParseExact(STRDATE,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat)
Just like someone above said you can send it as a string parameter but it must have this format: '20130121' for example and you can convert it to that format taking it directly from the control. So you'll get it for example from a textbox like:
date = datetextbox.text; // date is going to be something like: "2013-01-21 12:00:00am"
to convert it to: '20130121' you use:
date = date.Substring(6, 4) + date.Substring(3, 2) + date.Substring(0, 2);
so that SQL can convert it and put it into your database.
Worked for me below code:
DateTime date = DateTime.Parse(this.Text, CultureInfo.CreateSpecificCulture("fr-FR"));
Namespace
using System.Globalization;
You can use also
this.Text = "22112009";
DateTime newDateTime = new DateTime(Convert.ToInt32(this.Text.Substring(4, 4)), // Year
Convert.ToInt32(this.Text.Substring(2,2)), // Month
Convert.ToInt32(this.Text.Substring(0,2)));// Day
Also I noticed sometimes if your string has empty space in front or end or any other junk char attached in DateTime value then also we get this error message

Categories

Resources