I have to change a csv file with several dates in it. Every row starts with a date followed whith data.
11-nov-2015,data,data,data
10-nov-2015,data,data,data
9-nov-2015,data,data,data
With the following code I put the data in the right place (20141109 (yyyymmdd))
string[] values = lines1[i].Split(',');
if (values.Length >= 3)
{
string[] parts = values[0].Split('-');
if (parts.Length == 3)
{
values[0] = String.Format("{0}-{1}-{2}", parts[2], parts[1], parts[0]);
lines1[i] = String.Join(",", values);
}
}
But two problems remain:
1) The month has to change from nov to 11
2) In the file I download the day for example 9-nov-2014 has to change to 09. for 8-nov-2014 to 08. So an extra 0.
How can this be solved in C#
Instead of making your own datetime format parser, you should use the one already available for you. DateTime.TryParseExact is your tool to convert a string in a date when you know the exact format.
Converting back the date, in the string format that you like, is another task easily solved by the override of ToString() specific for a datetime
string[] values = lines1[i].Split(',');
if (values.Length >= 3)
{
DateTime dt;
if (DateTime.TryParseExact(values[0], "d-MMM-yyyy",
System.Globalization.CultureInfo.CurrentCulture,
System.Globalization.DateTimeStyles.None, out dt))
{
values[0] = dt.ToString("yyyyMMdd");
lines1[i] = String.Join(",", values);
}
}
I would parse the string into a date and then write it back using a custom date format. From this link we can write this code:
String pattern = "dd-MMM-yyyy";
DateTime dt;
if (DateTime.TryParseExact(values[0], pattern, CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt)) {
// dt is the parsed value
String sdt = dt.ToString("yyyyMMdd"); // <<--this is the string you want
} else {
// Invalid string, handle it as you see fit
}
Related
I am reading an input from a device on a comm port, that is a date in the following format "dd/MM/yyyy hh:mm" to a string value. I am trying to format the date to show "ddMMyyyy hh:mm:ss". I have tried the following but get the error below code:
(input value is "31/08/2018 02:32")
public string ParseLine(string Line)
{
var input = Line.Split(',');
var dateTime = DateTime.Parse (input[0]);
var Action = input[1] == "1" ? "ONL" : "OFL";
var readerAddr = input[1] == "1" ? "S" : "T";
var TagType = input[2];
var TagNum = input[3].Substring(TagType.Length);
return $"{Action},{TagNum},{readerAddr},{dateTime:ddMMyyyy hh:mm:ss}";
}
Any advise will be appreciated?
Use DateTime.TryParseExact to check if 'input[0]' has a valid datetime value. Example:
public string ParseLine(string Line)
{
...
if(!DateTime.TryParseExact(input[0], "ddMMyyyy hh:mm:ss", CultureInfo.CurrentCulture, DateTimeStyles.None, out var result))
{
//Is not a valid date :C
}
Console.WriteLine("Valid date: " + result);
}
In case date time would be in some weird format, you will need to use DateTime.ParseExact(..) method like this:
var dateTime = DateTime.ParseExact(input[0], "dd/MM/yyyy hh:mm");
However, your format is one of the accepted ISO formats, so it should work like you wrote down. The best reason why is does not work is that the value of input[0] is not what you expect, so at first check what this variable actually contains.
Thanks to everyone's comments and advise I managed to get it right by using these two methods:
var dateTime = DateTime.ParseExact(input[0], "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);
and
return $"{Action},{TagNum},{readerAddr},{dateTime:ddMMyyyy HH:mm:ss}";
I'm new to C#.
I have different file names. for example:
C:\Test\ABCD\Warranty_2018_02_12__13_25_13.743.xml
from this name I want to get the date, like 12.02.2018 13:25:13
So the files are never the same.
My code:
public string GetCreationDate(string fileResult)
{
int index = fileResult.IndexOf("_");
if (index != -1)
{
string date = fileResult.Substring(index + 1, 20);
char[] delimiter = new char[] { '_' };
string[] dateWithoutLines = date.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
Array.Reverse(dateWithoutLines, 0, 3);
//Here is the error
//Guess it's because of the 'ToString()'
DateTime dateTime = DateTime.ParseExact(dateWithoutLines.ToString(), "dd/MM/yyyy hh:mm:ss",
System.Globalization.CultureInfo.InvariantCulture);
return dateTime.ToString();
}
return null;
}
In the debugger I have now 6 strings in the dateWithoutLines with the right dates. like "12" "02" "2018" ...
But then it says that is it not a right DateTime Format there. Okay, but if I delete the
ToString()
It says it can't convert string[] to string. So what is wrong here?
No need to split the original string, reverse, combine and so on.
Let DateTime.TryParseExact do all the work for you:
Also, consider returning a nullable DateTime (DateTime?) instead of a string:
public DateTime? GetCreationDate(string fileResult)
{
int index = fileResult.IndexOf("_");
if (index <= 0)
return null;
// check for string length, you don't want the following call to fileResult.Substring to throw an exception
if (fileResult.Length < index+20)
return null;
string date = fileResult.Substring(index + 1, 20);
DateTime dt;
if (DateTime.TryParseExact(date, "yyyy_MM_dd__HH_mm_ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
return dt;
return null;
}
dateWithoutLines is a string[]. The ToString implementation for string[] yields "System.String[]" which is not a valid date. Furthermore DateTime.Parse does not take a string[], but only a string.
If the date format in the file name is always the same, you can use string.Format
var formattedDate = string.Format("{2}.{1}.{0} {3}:{4}:{5}", dateWithoutLines);
The numbers in the curly braces refer objects in the passed array by index, i.e. that {2} will be replaced by 12 in your example, {1} by 02 and so on. Please note that I've used the indices from the original order, not the reversed array.
Since you're parsing the date to format it, this way, no parsing is needed, since it's already formatted.
object instance dateWithoutLines is an array of strings , not a single string, thus you cant use method ToString().
So I believe you want something in the sense of :
foreach (string date in dateWithoutLines)
{
DateTime dateTime = DateTime.ParseExact(date, "dd/MM/yyyy hh:mm:ss",
System.Globalization.CultureInfo.InvariantCulture);
}
Notice, that since you have an array of strings, date is a string object so there is no need to call ToString() method for each date string instance
I have a value (as a date) that gets returned from the selected combobox item. I wish to convert this value to a proper DateTime string. Problem is the string from the combobox.selectedItem to convert is;
July 2016
and I want to convert it to (start of month always);
01/07/2016 12:00AM
Is there away of doing the in C#?
As the only way around it is to do I can think of;
if(combobox.selectedItem.Contains("July") && combobox.selectedItem.Contains("2016")) {
//startDate = Set date to 01/07/2016..
endDate = DateTime.Now().ToString();
}
which is not ideal at all...especially if I want do past 24+ months (as combobox is populated with each month between two dates from an xml file)
EDIT/UPDATE
See below working code based of the advice from BOB!
#region try set Date from selected background populated Month
try
{
//param/arg from backgroundWorker
string selectedDate = filterByMonthComboBoxParam;
//Could also be from direct combobox.selecteditem with system string removed
//string selectedDate = filterByMonthComboBox.SelectedItem.ToString().Replace("System.Windows.Controls.ComboBoxItem:", "");
for (int ifilterByMonthComboBox = 0; ifilterByMonthComboBox < filterByMonthComboBox.Items.Count; ifilterByMonthComboBox++)
{
string _filterByMonthComboBox = filterByMonthComboBox.Items[ifilterByMonthComboBox].ToString();
if (_filterByMonthComboBox.Contains(selectedDate)){
DateTime dtX;
if (DateTime.TryParseExact(selectedDate, "MMMM yyyy", null, DateTimeStyles.AllowWhiteSpaces, out dtX))
{
// Parse success
Console.WriteLine(dtX);
checkMinDate = dtX.ToString();
checkMaxDate = nowTime.ToString();
Console.WriteLine("Date Filter is:");
Console.WriteLine("Min: " + checkMinDate);
Console.WriteLine("Max: " + checkMaxDate);
}
else
{
// parse failed
Console.WriteLine("Failed");
}
}
}
}catch(Exception dateError){
Console.WriteLine(dateError);
}
#endregion try set Date from selected background populated Month
DateTime dt;
if (DateTime.TryParseExact("July 2016", "MMMM yyyy", null, DateTimeStyles.None, out dt))
{
// Parse success
Console.WriteLine(dt);
}
else
{
// parse failed
Console.WriteLine("Failed");
}
Checkout DateTime.TryParseExact() and the formats
Edit:
If the date have white space, either use string.Trim() on it or change DateTimeStyles.None to DateTimeStyles.AllowWhiteSpaces
I have passing a date in query string as the format of 02-2014.and using this date I done the search.It is working and the result is perfect .but when I change the query string value in the browser then the error will showing.In this condition I need only some message,So how can we check the query string date value is in correct format.my code is
string dateToSearch = HttpContext.Current.Request["date"];
if (!string.IsNullOrEmpty(dateToSearch))
{
dateToSearch = dateToSearch.Trim();
string year = null;
string month = null;
var dates = dateToSearch.Split("-".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (dates.Length > 0)
{
month = dates[0];
year = dates[1];
}
}
Just use DateTime.TryParseExact with the format string MM-yyyy. This will tell you whether your input string is in the format you specified and if so, it returns the parsed DateTime object via an out parameter.
Try this:
DateTime date;
if (DateTime.TryParseExact(text, "MM'-'yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date))
{
// Success
}
else
{
// Parse failed
}
How to Format a date pass as a parameter to a function and return data is a string with "yyyy/mm/dd" format ?
for example if I would want to format a string retrieved from textbox and I want a special function to format it and return as a string format.
string myDate = txtJoiningDate.Text,
my function should be :
public string GetFormattedDate(string myDate)
{
//Formating should happen here.
return myDate;
}
public string GetFormattedDate(String MyDateTime)
{
//Formating should happen here.
DateTime dt = DateTime.Parse(MyDateTime);
return dt.ToString("yyyy/MM/dd");
}
also can be done with this
string dt = DateTime.Parse(txtDate.Text.Trim()).ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
you need to parse the string to a DateTime object however you need to make sure that the format you are going to parse will work.
take a look at DateTime.Parse (or TryParse):
http://msdn.microsoft.com/en-us/library/1k1skd40.aspx
then you simply do:
// lets say you are creating your datetime:
DateTime dt = new DateTime(2013, 11, 1);
return dt.ToString("dd/MM/yyyy");
the above will return 01/11/2013
more information:
http://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
Hurrey.I got the answer.Working 100%. Hope will be helpful for others.
public string FormatPostingDate(object obj)
{
if (obj != null && obj.ToString() != string.Empty)
{
DateTime postingDate = Convert.ToDateTime(obj);
return string.Format("{0:yyyy/MM/dd}", postingDate);
}
return string.Empty;
}
also can be done with this
using System.Globalization;
string dt = DateTime.Parse(txtDate.Text.Trim()).ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);