I have 2 strings:
string d = "09/06/24";
string t = "13:35:01";
I want to take the strings and combine them to make a datetime variable:
newDT = Convert.ToDateTime(d + t);
Compiles but when it hits that line it fails..........any ideas?
DateTime.Parse(d + " " + t) should do it, the problem you were probably having is the lack of space inbetween the two variables, you were trying to parse:
"09/06/2413:35:01"
As you can see, this is not a valid date format.
does this work?
DateTime.Parse(d + " " + t);
Try this:
string d = "09/06/24";
string t = "13:35:01";
DateTime newDT = Convert.ToDateTime(d + " " + t);
If you have a specific format of date and time in the string, then consider using DateTime.TryParseExact which allows you to specify one or more formats to use for parsing.
Try:
Convert.ToDateTime(d + " " + t);
Convert.ToDateTime(d + " " + t) should also work.
Related
I'm trying to format content of my file like this:
0126252019-05-06 14:47:06 1098500020
But everytime I'm getting this results:
01262524. 5. 2019. 14:47:08 1098500020
Obliviously date and time are not formated as I wanted.
Here is my code:
StreamWriter file = new System.IO.StreamWriter("C:\\MyMainFolder\\MyFilesFolder\\" + 15050 + ".flr");
file.WriteLine(12625.ToString("D6") + string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now + " " + 1098500020));
file.Close();
I've tried to format DateTime.Now as I wrote
string.Format("{0:yyyy-MM-dd HH:mm:ss}"
But looks like its not working
Thanks guys
Cheers!
You are passing DateTime.Now + " " + 1098500020 to string.Format which isn't going to be parsed by that format string you have specified. To fix that you should move the ).
However, you should create the entire string, including the prefix, with string.Format, or for clearer code use string interpolation, for example:
var someInteger = 12625;
var line = $"{someInteger:D6}{DateTime.Now:yyyy-MM-dd HH:mm:ss} 1098500020";
The problem is that + is applied as string concatenation in the expression below:
string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now + " " + 1098500020);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// C# makes this one string, and passes it for formatting.
Moving the concatenation that you plan to do inside the format string will fix the problem:
string.Format("{0:yyyy-MM-dd HH:mm:ss} 1098500020", DateTime.Now);
I am trying to remove the last 6 characters from item.Size because the data has a decimal place and 5 trailing 0s in the database.
sb.Append("<div>" + item.Size + " " + item.Units + " </div>");
ie. item.Size is displayed as 1.00000 and I need it to just be displayed as 1.
This is part of a StringBuilder, and as I'm new to coding, not even sure the right way to go about this.
sb.Append("<div>" + (int)item.Size + " " + item.Units + " </div>");
StringBuilder has the same formatting capabilities as String.Format when you use the AppendFormat method:
sb.AppendFormat("<div>{0:N0} {1} </div>", item.Size, item.Units);
The format string "N0" tells it to format the number with 0 decimal points. That assumes the item.Size is stored as a numerical type. If not, simply remove the part of the string you don't want:
sb.AppendFormat("<div>{0} {1}</div>", item.Size.Split('.')[0], item.Units);
Here I've used Split, assuming that the value is actually something like what you've shown in your example.
Better you use int.TryParse(or Int32.TryParse) method. because if item.Size is not convertible to int, then it wont give you any exception. you can use int or long according to your choice. So you can handle this in your code according to the if/else condition.
Sample Code:
int size;
string str = "";
if(int.TryParse(str, out size) == true)
{
}
else
{
}
I know this may seem a junior question and it should have been easy to find the solution by Googling it but I am stuck.
I am using C#.
I have this string:
20150824100112345 (for instance)
I wish to transform it to a new string like so:
2015\08\24\10\00\01\12\345
Is there a '1-liner' of code I can use to accomplish this please?
NB
Without 1st converting it to a datetime format
As said in the comments, you should really parse it to a DateTime and then turn that into a string.
But to parse a string as you asked you should use a Regex which can split it into groups.
If you don't want to parse to DateTime first (i.e. if you don't care about validity) and if the input is always formatted as your example (zero-padded, so 08 instead of 8), you can do with a few simple Substring() calls:
string input = "20150824100112345";
string output = input.Substring(0, 4) + #"\" // 2015
+ input.Substring(4, 2) + #"\" // 08
+ input.Substring(6, 2) + #"\" // 24
+ input.Substring(8, 2) + #"\" // 10
+ input.Substring(10, 2) + #"\" // 01
+ input.Substring(12, 2) + #"\" // 12
+ input.Substring(14, 3); // 345
Or in Regex:
string input = "20150824100112345";
string output = Regex.Replace(input,
"([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{3})",
#"$1\$2\$3\$4\$5\$6\$7");
I have made a code like this:
TextWriter tw = File.CreateText(#"D:\output.txt");
tw.Write(#"{""lon"":" + grid.point[0].ToString("###.####") + ",");
tw.Write(#"""latt"":" + grid.point[1].ToString("###.####") + ",");
char c = '"';
////improve the last line pls
tw.Write(#"""color"":" + c.ToString() + "#" + grid.Color.ToString("X").Substring(2) + c.ToString() + "},\n");
With the above code, I had successfully made a JSON format look like below:
{"lon":121,"latt":40.5025,"color":"#3EC1FF"},
Now My question is:
How to improve the string format without using the c.toString()?
You can use the format overload of the Write method e.g. Write(String, Object[]).
Something like this:
tw.Write("\"color\":\"#{0}\"}},\n", grid.Color.ToString("X").Substring(2));
StringBuilder jsonBuilder=new StringBuilder();
jsonBuilder.AppendFormat("{0}", "{");
jsonBuilder.AppendFormat("\"Lat\":{0:0.000},", 584.25689);
jsonBuilder.AppendFormat("\"Lon\":{0:0.000},", 784.25689);
jsonBuilder.AppendFormat("Color:{0}","\"#3EC1FF\"");
jsonBuilder.AppendFormat("{0}", "}");
string json = jsonBuilder.ToString();
I am trying to save a number of images and I'd like to use the DateTime to have distinct and identifiable Filenames.
So I create a String with the correct Path, add the datetime to it and remove the spaces, dots and colons.
String imagePath = "D:\\Patienten\\" + username;
imagePath += "\\"+DateTime.Now.ToString();
Console.WriteLine("WithFilename: " + imagePath);
imagePath.Replace(" ", "");
Console.WriteLine("Without \" \" : " + imagePath);
imagePath.Replace(".", "");
Console.WriteLine("Without \".\": " + imagePath);
imagePath.Replace(":", "");
Console.WriteLine("Output format: " + imagePath);
imagePath += ".png";
image.Save(imagePath);
According to the console output the String doesnt change at all.
Meaning all the Output Strings from Console.Writeline are identical.
I am using c# in visual Studio Express 2010 in case that makes a difference.
Can anyone find an Error here?
Thanks in advance!
Strings are immutable, the modified string will be a new string that is returned from the function
e.g.
imagePath = imagePath.Replace(" ", "");
Why strings are immutable
Why not just use DateTime.ToString() with a format and drop the dividers using that? Would be more efficient than performing several String.Replace() yourself:
string imagePath = "D:\\Patienten\\" + username + "\\" + DateTime.Now.ToString("yyyyMMdd hhmmssfff") + ".png";
You should use:
imagePath = imagePath.Replace(" ", ""); You should assign returned value
From the documentation (emphasis mine):
Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
It is supposed to work like that. Use
imagePath = imagePath.Replace(" ", "");
instead.