DateTime format is not getting changed in C# - c#

I am working on an already developed desktop application in VS 2010 with MS Access database. The application works well in dd/MM/yyyy format. But the following code uses Convert.ToDateTime which changes datetime string in dd/MM/yyyy to the system's format and hence gives error.
for (int i = 0; i <= (Convert.ToDateTime(dtp_Date.Text) - Convert.ToDateTime(dt.Rows[0]["Dat"].ToString())).TotalDays; i++)
{
double dtSale = _objCashInHand.getSaleSum(Convert.ToDateTime(dt.Rows[0]["Dat"].ToString()).AddDays(j).ToShortDateString().ToString());
double dtPurchase = _objCashInHand.getPurchaseSum(Convert.ToDateTime(dt.Rows[0]["Dat"].ToString()).AddDays(j).ToShortDateString().ToString());
double dtEventOrder = _objCashInHand.getEventOrder(Convert.ToDateTime(dt.Rows[0]["Dat"].ToString()).AddDays(j).ToShortDateString().ToString());
double dtCredit = _objCashInHand.getCreditSum(Convert.ToDateTime(dt.Rows[0]["Dat"].ToString()).AddDays(j).ToShortDateString().ToString());
double dtDebit = _objCashInHand.getDebitSum(Convert.ToDateTime(dt.Rows[0]["Dat"].ToString()).AddDays(j).ToShortDateString().ToString());
double previousvalue = Convert.ToDouble(dgv_Cash.Rows[(i + 1) - 1].Cells["OpeningAmount"].Value.ToString());
dgv_Cash.Rows.Add(Convert.ToDateTime(dt.Rows[0]["Dat"].ToString()).AddDays(j).ToShortDateString(), dtSale, dtEventOrder, dtPurchase, dtCredit, dtDebit, (previousvalue + Convert.ToDouble(dtSale) + Convert.ToDouble(dtEventOrder) - Convert.ToDouble(dtPurchase) + Convert.ToDouble(dtCredit) - Convert.ToDouble(dtDebit)).ToString());
j++;
}
I tried using DateTime.ParseExact(dtp_Date.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture) but the datetime format is still in system's format.
What do I do to keep the datetime format in dd/MM/yyyy even in the for loop for proper working?

You need to specify Invariantculture when converting DateTime to string as well.

Related

Convert MM:SS string to HH:MM:SS in C#

I have this piece of code which works nicely to convert HH:MM:SS to seconds as an integer.
for (int i = 0; i < nrdaily.Rows.Count; i++)
{
double NRT = TimeSpan.Parse(nrdaily.Rows[i][3].ToString()).TotalSeconds;
nrdaily.Rows[i][3] = NRT;
}
However, I have a CSV file I'm dealing with where a field has many values that are stored in MM:SS format and TotalSeconds seems to misinterpret it as HH:MM and gives a false result.
How could I check the string to see if it's in HH:MM:SS format, and if it is in MM:SS convert it to HH:MM:SS?
Use TimeSpan.ParseExact
Example:
var testString = "01:05";
TimeSpan.ParseExact(testString, "mm\\:ss", CultureInfo.InvariantCulture).TotalSeconds;
//TotalSeconds will be 65
You could check the string length for starters to identify the format.
for (int i = 0; i < nrdaily.Rows.Count; i++)
{
string time = nrdaily.Rows[i][3].ToString();
if (time.Length == 5)
time = "00:" + time;
double NRT = TimeSpan.Parse(time).TotalSeconds;
nrdaily.Rows[i][3] = NRT;
}
Checking length is a very simplistic approach. To identify the format more accurately, you could use regular expressions.

String to DateTime conversion Failing

I'm trying to convert a string from a text file to a DateTime, but I'm getting weird results. On one computer, it works, but another, it doesn't. How would I make this work on all computers? On my last question, you said to add the culture thing, and it worked for a few minutes, but it's not working again now. Heres my code:
string[] stringArray = File.ReadAllLines("C:\\Program Files\\PointOfSales\\RecordTotals.txt");
int lines = stringArray.Length;
for (int i = 0; i < (lines / 5); i++)
{
TransactionList.Add(new Transaction
{
TotalEarned = Convert.ToDouble(stringArray[(i * 5)]),
TotalCost = Convert.ToDouble(stringArray[(i * 5) + 1]),
TotalHST = Convert.ToDouble(stringArray[(i * 5) + 2]),
Category = stringArray[(i * 5) + 3],
HoursSince2013 = Convert.ToDateTime(stringArray[(i * 5) + 4], CultureInfo.InvariantCulture)
});
}
I'm getting the error String was not recognized as a valid DateTime.
Any clues whats up? Thanks!
Edit: Using MessageBox.Show(stringArray[(i * 5) + 4]); I get 26/10/2013 11:58:03 AM
Edit: Why won't this work to convert current time to the right culture?
DateTime Today = DateTime.Now;
Today = DateTime.ParseExact(Today.ToString(), "dd/MM/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);
Your string, on that system, is not a valid date in invariant culture: 26/10/2013 11:58:03 AM. The invariant culture expects month/day/year, not day/month/year.
You should specify the same culture that is being used to generate the file that you are reading. You will need to have some way to determine or standardize on the cultures being used for writing to the file, as well as reading from it.
Edit: Why won't this work to convert current time to the right culture?
That will fail if your current culture doesn't use dd/MM/yyyy for it's format. Today.ToString() doesn't have a culture specified, or a format, so it's going to, on a US system, write out using MM/dd/yyyy format, which will cause the call to fail.
In your case, I would recommend always reading and writing using the same culture - If you write your file using: theDate.ToString(CultureInfo.InvariantCulture), then you can read using Convert.ToDateTime(theString, CultureInfo.InvariantCulture), and it will work on any system, since the same rules (Invariant culture) are used for both writing and reading.
You should use custom "dd/MM/yyyy HH:mm:ss t" format with InvariantCulture like;
string s = "26/10/2013 11:58:03 AM";
DateTime dt = DateTime.ParseExact(s, "dd/MM/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);
Console.WriteLine(dt);
Output will be;
10/26/2013 11:58:03 AM
Here a demonstration.
For more information, take a look at;
Custom Date and Time Format Strings
EDIT: If your DateTime.Now doesn't fit "dd/MM/yyyy HH:mm:ss tt" format, your program will fail. You should use InvariantCulture in all your programs with your DateTime.Now format exactly.

Windows Service gives String was not recognized as a valid DateTime exception but the same code running properly in Console Application

Windows Service gives String was not recognized as a valid DateTime exception but the same code running properly in Console Application
Object max = cmd.ExecuteScalar(); //max will have 6/30/2012 12:00:00 AM
DateTime currentDt = DateTime.Now;
currentDt = DateTime.ParseExact(max.ToString(), "M/d/yyyy h:mm:ss tt", CultureInfo.CurrentCulture.DateTimeFormat); //This Line Gives Error in WindowsService Only
StreamWriter sw = new StreamWriter("E:\\ram\\SampleService.txt", true);
sw.WriteLine(currentDt.ToString());
sw.Close();
I even Changed System DateTime Format Settings to Engish - Us Settings.ShortDatetime is M/d/yyyy and Longtime is h:mm:ss tt.
Can someone help me resolve this issue?
My guess is that the system locale isn't the same as your user locale. If your system locale uses something other than "/" as the date separator, it will fail to match the "/" in your format string.
I suggest you change to use CultureInfo.InvariantCulture, at which point it should work - if the value of max.ToString() is actually "6/30/2012 12:00:00 AM". Have you validated that in the case it's failing, that's the value you're getting?
If your value is coming from a database though, why is it stored as a string to start with? Are you sure it even is a string? If it's actually a DateTime, then when you call ToString() you'll be using the current culture's default format to convert it - which could easily fail on the way back. Even if it is a string at the moment, does it really have to be? The fewer string conversions you can introduce, the better.
(As an aside, it's simpler to use File.WriteAllText or File.AppendAllText than using a StreamWriter like this. If you do need to use a StreamWriter, remember to use a using statement to dispose of the resource properly.)
Does your SQL request return DateTime or String value?
Also I don't see why do you use ParseExact in this case. In your case I would suggest to use Parse method with InvariantCulture parameter:
currentDt = DateTime.Parse(max.ToString(), CultureInfo.InvariantCulture);
If your max value is DateTime then you don't need to do parsing at all. You just need to check if it is DBNull.Value:
if (max != DBNullValue)
{
currentDt = (DateTime)max;
}
Try it without the CultureInfo:
currentDt = DateTime.ParseExact(max.ToString(), "M/d/yyyy h:mm:ss tt", null);
I got same problem when i had been building windows service.In that, i tryed to convert string date to datetime format. For that i used format string date_time = Day + "/" + Mn + "/" + Yr + " " + Hr + ":" + Min; and tryed convert it to datetime().
This format was running properly in windows form application but not in Windows service project.
Solution :
I changed above string format with this format string date_time = Mn + "/" + Day + "/" + Yr + " " + Hr + ":" + Min;, And then passed it to datetime().
Like follow :
string date_time = Mn + "/" + Day + "/" + Yr + " " + Hr + ":" + Min;
DateTime dt_1 = Convert.ToDateTime(date_time);
By default the en-US culture is used by .NET according to which the Date is in Month/Day/Year format
This is 100% working.

C# with Gridview, Access, DateTime and converting

I have been going through the motions and still cannot seem to get this right. I have textboxes in a gridview that are populated from an access database. They are all datetime values. In the backend code, I am trying to loop through all those values and then apply conditional formatting. For some unknown reason I am unable to get the value from those textboxes in the gridview and when I do, they are seen by the app as string as opposed to datetime. Converting is futile as the same error, "String was not recognized as a valid DateTime." keeps popping up.
Any ideas on how to get values from a gridview textbox, and then convert them from a string to a datetime format?
Here is the code thus far...
for (int p = 0; p < rowscount; p++)
{
var myLabel2 = (TextBox)GridView1.Rows[p].Cells[0].FindControl("Label2");
var myLabel4 = (TextBox)GridView1.Rows[p].Cells[0].FindControl("Label4");
DateTime start = Convert.ToDateTime(myLabel2.Text).Date;
DateTime now = DateTime.Now.Date;
DateTime end = Convert.ToDateTime(myLabel4.Text).Date;
if (now >= start && now <= end)
{
myLabel2.BackColor = Color.Chartreuse;
myLabel4.BackColor = Color.Chartreuse;
myLabel7.BackColor = Color.Chartreuse;
myLabel9.BackColor = Color.Chartreuse;
}
else
{
myLabel2.BackColor = Color.White;
myLabel4.BackColor = Color.White;
myLabel7.BackColor = Color.White;
myLabel9.BackColor = Color.White;
}
}
Thanks in advance
This looks like datetime format issue. Your GridView converts datetime into string in one way and you're trying to convert it back to datetime using different format. Instead of Convert.ToDateTime try using DateTime.ParseExact(String, String, IFormatProvider):
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "dd/MMM/yyyy h:mm tt zzz";
DateTime result = DateTime.ParseExact(dateString, format, provider);
Use format that applies to your case.
Are the textboxes both in the first column of GridView1? For the code:
var myLabel2 = (TextBox)GridView1.Rows[p].Cells[0].FindControl("Label2");
var myLabel4 = (TextBox)GridView1.Rows[p].Cells[0].FindControl("Label4");
It means the names of your textboxes are "Label2" and "Label4", and they are both in the first column as you use Cells[0] to fetch them. Your have to make sure of that.
You can add break point to the above code, and debug it. You can see if myLabel2 and myLabel4 have any value.
DateTime date = DateTime.ParseExact(myLabel2.Text, "dd/MM/yyyy", null);

Find highest DateTime from list of DateTime's

My Question is that, I want to find the highest DateTime from a list of DateTime?
I have one Array suppose string[] btime = new string[100];
In that Array I am storing the Date which is coming from the SQL-Server
The SQL Query is [CONVERT(varchar(10),GETDATE(),101)] it is returning the Date in format of MM/dd/yyyy
and then after I am concatenating the Date with my own given Time
i.e .btime[j] = SqlServerDate + " " + 15:20; and so on;
Now, from this given Array I want to find highest Date and Time
So, I have use this logic
string large=""
large=btime[0];
for (int i = 0; i < j; i++)
{
if (DateTime.Compare(DateTime.Parse(btime[i]),DateTime.Parse(large)) > 0)
{
large = btime[i];
}
}
but I am getting the Error at
if(DateTime.Compare(DateTime.Parse(btime[i]),DateTime.Parse(large)) > 0)
The Error is String not recognized as valid DateTime This error is occurring because of my System DateTime Format is yyyy/dd/MM
So Plz any one can help me in solving this problem
I don't want to change format of the system
Others have suggested different ways of parsing the DateTime. This seems pointless to me - if you can possibly change the query, just avoid performing the conversion to a string in the first place. The fewer conversions you use, the fewer chances you have for this sort of thing to be a problem.
Change the query so you end up with DateTime values, and then finding the latest one is trivial in LINQ:
DateTime latest = dateTimes.Max();
Hum,
// Containing your datetime field
string[] btime = new string[100];
var max = btime.Select(s => DateTime.Parse(s, "MM/dd/yyyy", CultureInfo.InvariantCulture)).Max();
Use the DateTime.ParseExact Method.
Example:
CultureProvider provider = CultureInfo.InvariantCulture;
DateTime.ParseExact(btime[i], "yyyy/dd/MM", provider);
you, can use DateTime.ParseExact() functionality to do this. Refer the following code part.
CurDate = DateTime.ParseExact(Name3, "yyyyMMddhhmmssffff", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None)
You can use the DateTime.ParseExact() method.
CultureProvider provider = CultureInfo.InvariantCulture;
DateTime.ParseExact(btime[i], "MM/dd/yyyy HH:mm", provider);
The second parameter there is the format string. This specifies how your date will be formatted.
Since you are adding a 24 hour time at the end you need the HH:mm (HH says expect a 24 hour time).
Thanks to everyone.
I have got some sort of answer:
string large = "";
large = btime[0];
IFormatProvider culture = System.Threading.Thread.CurrentThread.CurrentCulture;
// This Code will convert the System Format in Thread, Not the Actual Format
// of The System
CultureInfo ciNewFormat = new CultureInfo(CultureInfo.CurrentCulture.ToString());
ciNewFormat.DateTimeFormat.ShortDatePattern = "MM/dd/yyyy";
System.Threading.Thread.CurrentThread.CurrentCulture = ciNewFormat;
for (int i = 0; i < TimeBackupCounter; i++)
{
if (DateTime.Compare(DateTime.Parse(btime[i]),DateTime.Parse(large)) > 0)
{
large = btime[i];
}
}

Categories