Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am using this in my controller:
char[] arrDate = date.ToArray();
DateTime dt = DateTime.Parse(arrDate[0] + arrDate[1] + "/" +
arrDate[2] + arrDate[3] + "/" +
arrDate[4] + arrDate[5] + arrDate[6] + arrDate[7]);
The error:
System.FormatException: String was not recognized as a valid DateTime.
Consider this:
var date = "11252017";
var arrDate = date.ToArray();
var strDate = arrDate[0] + arrDate[1] + "/" +
arrDate[2] + arrDate[3] + "/" +
arrDate[4] + arrDate[5] + arrDate[6] + arrDate[7]; // 98/25/2017
Notice that:
'1' + '1' = 98* ⇒ char + char = int
98 + "/" = "98/" ⇒ int + string = string
"98/" + '2' = "98/2" ⇒ string + char = string
The fix:
var dt = DateTime.Parse("" +
arrDate[0] + arrDate[1] + "/" +
arrDate[2] + arrDate[3] + "/" +
arrDate[4] + arrDate[5] + arrDate[6] + arrDate[7]);
*ASCII representation:
'1' in decimal is 49
I assume date is of type string. For parsing a string the DateTime class has several methods of which ParseExact is one. This method can parse a string given a format specifier and a culture. In your case the date can be parsed like this:
var date = "11252017";
var dt = DateTime.ParseExact(date, "MMddyyyy", CultureInfo.InvariantCulture);
By the way a string is an array of chars, so in your code arrDate[0] is exactly the same as date[0]. Just something to keep in mind for the future.
Related
This question already has answers here:
Binding Listbox to List<object> in WinForms
(8 answers)
Closed 3 years ago.
I write a program, it is necessary to switch the current status in it, as well as it is necessary to plan it when you plan an event, it is perceived as an object, the object has its own fields, such as the start time and end time of the event, I want this object to be output when generated sheet boxing.
Tell me how can this be done?
List<ChangeStatus> events = new List<ChangeStatus>();
private void toPlanButton_Click(object sender, EventArgs e)
{
string comboBoxTypeNumber = comboBoxType.SelectedItem.ToString();
DateTime Time = new DateTime();
Time = dateTimePicker1.Value;
DateTime longTime = new DateTime();
longTime = dateTimePicker2.Value;
ChangeStatus statusEvent = new ChangeStatus();
statusEvent.StartEvent = Time;
statusEvent.LongEvent = longTime;
statusEvent.TypeEvent = comboBoxTypeNumber;
events.Add(statusEvent);
TimeComparer tc = new TimeComparer();
events.Sort(tc);
}
How to display an object in listbox?
It is necessary to display a list of objects, because in the future I want to make editing objects
listBoxEvent.Items.Add("type: " + statusEvent.TypeEvent + ";" + " start: " + statusEvent.StartEvent + ";" + " long: " + statusEvent.LongEvent + " min;"); - work
You can use System.Linq Linq to get the string text and can call the AddRange() method on Items collection like
List<string> listData = events.Select(x => "type: " + x.TypeEvent + ";" + " start: " + x.StartEvent + ";" + " long: " + x.LongEvent + " min;").ToList();
listBoxEvent.DataSource = listData;
I have a string variable with it's value formatted to look like "1:23:45 AM"
I need to convert that into a DateTime variable for time without a date component.
I am receiving an "Unhandled exception" error that is being caused by the formatting. If I remove the "AM", it works fine but the "AM/PM" component is needed for what I am trying to do.
I am currently using the following code to attempt this...
"temp" is the name of the variable I am using until I come up with a more meaningful variable name...
public string PlusMinus12(string hour, string minute, string second, string ampm)
{
string PlusMinus;
int rndmTmp1 = Random1();
int rndmTmp2 = Random2();
if (rndmTmp1 == 0)
{
PlusMinus = hour + ":" + minute + ":" + second + ": " + ampm;
return PlusMinus;
}
else if (rndmTmp1 == 1)
{
string temp = hour + ":" + minute + ":" + second +": " + ampm;
**DateTime subtract = DateTime.Parse(temp);**
subtract.AddSeconds(-rndmTmp2);
PlusMinus = subtract.ToString("h:mm:ss tt");
return PlusMinus;
}
else
{
DateTime subtract = DateTime.Parse(temp); is the line causing the error
The error is:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: String was not recognized as a valid DateTime.
Most of the information I have found so far on this topic include solutions that depend on the existence of the Date component, which I am not using.
Any ideas?
Thank you
You should try parsing it using DateTime.ParseExact using a custom format from here: Custom Date and Time Format Strings
Your problem is this
PlusMinus = hour + ":" + minute + ":" + second + ": " + ampm;
Change it to
PlusMinus = Int32.Parse(hour).ToString("00") + ":" + Int32.Parse(minute).ToString("00") + ":" + second.ToString("00") + " " + ampm;
A little convoluted since strings are passed in as input. No colon after the seconds and zero pad the numbers. Also, since they are input variables, at some point you should verify that they are between 0-59.
If you're only interested in returning the time part, add a extra variable that holds the date part and append it to the front of temp when you parse it?
like:
string tempDate = "2008-05-01 "
This works for me:
string timeString = "1:23:45 AM";
string format = "h:mm:ss tt";
CultureInfo provider = CultureInfo.InvariantCulture;
try
{
DateTime result = DateTime.ParseExact(timeString, format, provider);
Console.WriteLine("{0} converts to {1}.", timeString, result.ToString());
}
catch (FormatException)
{
Console.WriteLine("{0} is not in the correct format.", timeString);
}
Probably your issue is with a particular time.
UPDATE: You need to check you are passing minutes and seconds to this function with a 0 for values like 1-2..9. Because standard provider will not accept a string like '1:1:2 AM'.
public string PlusMinus12(string hour, string minute, string second, string ampm)
{
string PlusMinus;
int rndmTmp1 = Random1();
int rndmTmp2 = Random2();
if (rndmTmp1 == 0)
{
PlusMinus = hour + ":" + minute + ":" + second + ": " + ampm;
return PlusMinus;
}
else if (rndmTmp1 == 1)
{
string temp = hour + ":" + minute + ":" + second +": " + ampm;
DateTime subtract = DateTime.Parse("2000-01-01 " + temp);
subtract.AddSeconds(-rndmTmp2);
PlusMinus = subtract.ToString("h:mm:ss tt");
return PlusMinus;
}
else
{
This question already has answers here:
Escape double quotes in a string
(9 answers)
How can I add double quotes to a string that is inside a variable?
(20 answers)
Closed 7 years ago.
I have been looking at this for a while trying everything I can find on SO. There are many posts but I must be missing something.
I am building a string and need to get a double quote in it between two variables.
I want the string to be
convert -density 150 "L:\03 Supervisors\
The code is
tw.WriteLine(strPrefix + " " + strLastPath);
where
strPrefix = convert -density 150
and
strLastPath = L:\\03 Supervisors\
I have tried many combinations of "" """ """" \" "\ in the middle where the space is being inserted.
Please show me what I am missing.
You have two options:
var output1 = strPrefix + "\"" + strLastPath;
Or using a verbatim string:
var output2 = strPrefix + #"""" + strLastPath;
Here's a sample console application that achieves what you're after:
namespace DoubleQuote
{
class Program
{
static void Main(string[] args)
{
var strPrefix = "convert - density 150";
var strLastPath = #"L:\\03 Supervisors\";
Console.WriteLine(strPrefix + " \"" + strLastPath);
Console.ReadKey();
}
}
}
If written as a format string it would look like this:
var textToOutput = string.Format("{0} \"{1}", strPrefix, strLastPath);
Console.WriteLine(textToOutput);
Please try this
var strPrefix = "convert -density 150";
var strLastPath = #"L:\03 Supervisors\";
Console.WriteLine(strPrefix + " " + '"'+strLastPath);
This question already has answers here:
String format currency
(8 answers)
Closed 8 years ago.
I need to format my display tostring results to a currency in C#
display = "Service Amount: " + service + "<br>" +
"Discount Amount: " + discountAmount + "<br>" +
"Total: " + total + "<br>";
lblDisplay.Text = display;
I did try the following:
display = "Service Amount: " + Console.Write(int.ToString("c",service)) + "
but I couldn't figure out what variables to put in. I just need it to display as $35.00 after the it returns the string.
Try:
display = string.Format("Service Amount: {0}",service.ToString("C"));
Console.WriteLine(display);
You can also look at StringBuilder for building strings or String.Format
String.Format("Service Amount: {0:C}<br>", service)
I currently am reading from a text file an assortment of data, and parsing out everything. One of the items being parsed out is a start time for an event in the format of:
yyMMddHHmm
1306050232
I then parse out to the following:
string year = "20" + time[0].ToString() + time[1].ToString();
string month = time[2].ToString() + time[3].ToString();
string day = time[4].ToString() + time[5].ToString();
string hour = time[6].ToString() + time[7].ToString();
string minute = time[8].ToString() + time[9].ToString();
string ampm ="";
int hourInt = Convert.ToInt32(hour);
if (hourInt <= 12)
{
time = month + "." + day + "." + year + "#" + hour + ":" + minute + " " + "AM";
ampm= "AM";
}
else
{
hourInt = hourInt - 12;
time = month + "." + day + "." + year + "#" + hourInt.ToString() + ":" + minute + " " + "PM";
ampm= "PM";
}
once these are parsed out, i combined the variables, and try to put it into a DateTime.
string tempStartTime = year + "-" + month + "-" + day + " " + hour + ":" + minute + " " + ampm;
string starttime = DateTime.ParseExact(tempStartTime, "yyyy-MM-dd HH:mm tt",null);
my issue is, I get a warning like this from the try catch:
System.FormatException: String was not recognized as a valid DateTime.
at System.DateTime.ParseExact(String s, String format, IFormatProvider provider)
at Project.GUI.parseSchedule(Int32 count)
I don't understand why, or how to correctly do this.
All I want is to take the start time from the file, convert it to a datetime object, and operate on it afterwards.
Why not simply parse with the format you are starting with?
var dt = DateTime.ParseExact(time, "yyMMddHHmm", CultureInfo.InvariantCulture);
There's no need for all of the pre-processing you're doing.
Parsing before parsing is generally quite unnecessary. If you have the input string
// yyMMddHHmm
string timestampString = "1306050232";
Then you should be able to do:
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime timestamp = DateTime.ParseExact(timeStampString, "yyMMddHHmm", provider);
If not, I would like to have more information about the exact error you are getting.
Have a look at DateTime.ParseExact()
http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
DateTime result=null;
CultureInfo provider = CultureInfo.InvariantCulture;
// Parse date and time with custom specifier.
string dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
string format = "ddd dd MMM yyyy h:mm tt zzz";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
You might want to look into custom formatters rather than trying to parse everything. I think that would make your code more maintainable, and probably somewhat easier to decode. There's a tool linked on that page that would let you test your format string before putting it into code, as well.