Convert MM:SS string to HH:MM:SS in C# - 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.

Related

DateTime format is not getting changed in 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.

Delete files which are older than today's date

I have some files in the format of "yyyyMMdd_hhmmss_abc.txt" in a particular location.
using the below code i am able to get all the files with "_abc.txt" in that folder.
fileArray = Directory.GetFiles(#"C://Documents", "*abc.txt");
for (int i = 0; i < fileArray.Length; i++)
{
fileArray[i] = Path.GetFileNameWithoutExtension(fileArray[i]);
Console.WriteLine(fileArray[i]);
}
But now I'm thinking of reading the file name, split it and then convert into date time object so that i can check for the condition(older than today's date) and delete them.
for eg: 20160426_045823_abc.txt
I want to split it into 2016, 04 , 26 and then convert into date time object using
Datetime d1 = new Datetime(2016,04,26) and then do other operations.
Is there any other way to solve this problem?
Thanks in advance
The following code can be used to get the collection of files having created date less than today's date, A simple iteration over the collection will help you to delete them as well: consider the code
Simple option:
foreach (var item in Directory.GetFiles(#"C://Documents", "*.txt")
.Where(x => new FileInfo(x).CreationTime.Date < DateTime.Now.Date))
{
File.Delete(item);
}
Based on Filename:
var fileArray = Directory.GetFiles(#"C://Documents", "*abc.txt");
for (int i = 0; i < fileArray.Length; i++)
{
DateTime fileNameTime;
string fileName = Path.GetFileNameWithoutExtension(fileArray[i]).Replace("_abc", " ");
fileNameTime = DateTime.ParseExact("yyyyMMdd_hhmmss", fileName, CultureInfo.InvariantCulture, DateTimeStyles.None);
if (fileNameTime.Date < DateTime.Now.Date)
{
File.Delete(fileArray[i]);
}
}
Please note : The best and effective option is the first one, what you need to do is assign the file-name as the dateTime at the time of
creation of the file(if it is under your control) so that the things
became easier for you
The filename is already in a sortable format based on the date. Instead of parsing bits of the filename into a DateTime object, why not create a filename based on today's date and filter your array of filenames down to only those that are string-comparison-less than your today's-date filename? It's probably quite a bit faster than doing date parsing on each filename, for large lists of files.
For example:
var path = "c:\\whatever";
var suffix = "_abc.txt";
var todaysFilename = DateTime.Now.ToString("yyyyMMdd_hhmmss") + suffix;
var filesToDelete = Directory.EnumerateFiles(path, "*" + suffix)
.Select(Path.GetFileName)
.Where(fileName => string.Compare(fileName, todaysFilename, StringComparison.Ordinal) < 0)
.ToArray();
foreach (var file in filesToDelete)
{
File.Delete(Path.Combine(path, file));
}
You could take the name of the string and do a DateTime.ParseExact.
String dateString = Path.GetFileNameWithoutExtension(fileArray[i])
DateTime d5 = DateTime.ParseExact(dateString, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None)
if (d5.Date < DateTime.Now.Date)
{
File.Delete(fileArray[i]);
}
This will take the first 8 characters of the string and parse do an exact parse on it.
Also you will probably just want the filename without the path and extension.
https://msdn.microsoft.com/en-us/library/w2sa9yss%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
You can get the DateTime a file was created like this
DateTime time = File.GetCreationTime(fileName);
Yes it's that easy.

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

How to convert a date of integers to a formated date string (i.e. 2012009 to 2/01/2009)

Any ideas?
I can't come up with any.
I have a list of dates I'm loading in from a csv file and they are saved as all integers, or rather a string of integers (i.e. Jan 1, 2009 = 1012009)
Any ideas on how to turn 1012009 into 1/01/2009?
Thanks!
Since the date is stored as a string, you may want to use ParseExact:
DateTime date = DateTime.ParseExact("28012009", "dMMyyyy", null);
ParseExact will throw an exception if the format doesn't match. It has other overloads, where you can specify more than a single possible format, if that is required. Note that here provider is null, which uses the current culture.
Depending on style you may wish to use TryParseExact.
int date = 1012009;
var month = date / 1000000;
var day = (date / 10000) % 100;
var year = date % 10000;
var formatted = new DateTime(year, month, day).ToString();
This assumes month-day-year; if the numbers are day-month-year, I’m sure you’ll be able to swap the month and day variables to accommodate that.
If you want to customise the date format, you can do so as described in:
Standard Date and Time Format Strings
Custom Date and Time Format Strings
Let 10102009 be dateInt.
string dateString = dateInt.ToString();
int l = dateString.Length;
dateString = dateString.Insert(l-3,"/");
dateString = dateString.Insert(l-6,"/");
You should now have 1/01/2009 in dateString.. You can also try the ParseExact function..

Categories