Split Dates from String in C# - c#

I have a String like this:
19.11.2022 /20.11.2022 + 17.12.2022 /18.12.2022 + 14.01.2023 /15.01.2023 + 11.02.2023 /12.02.2023 + 12.03.2023 + 23.04.2023
OR THIS
15.01.2023 (13:30 - 15:00 Uhr)
OR THIS
04.03.2023 + 05.03.2023
Or any more.
Now i want to split the dates and write to xml. But how i can Split them in C#?
I Tried nothing at the Moment because I have no idea.

String.Split and DateTime.Parse are likely a good place to start.

Related

String.Format is not working as expected C#

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);

How to slice/trim this value?

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
{
}

Quickest/Best way to Format a string

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");

Double ToString() no scientific notation not returning a string for 0.0

I need to return the string representation of a double in decimal notation rather than scientific and I used a modified version of the accepted solution here:
Double ToString - No Scientific Notation
private static readonly string format = "." + new string('#', 324);
foo.ToString(format);
This works well other than for a value that equals zero i.e. 0, 0.0, 0.000 etc where it returns an empty string.
What would be the easiest way to return a string representing 0 for any value of zero.
I don't mind if the string is 0 or 0.0 etc as long as it is numerical and not scientific.
Edit: I know I could add a conditional statement to check if the string is empty but I am interested to see if there is a way to do it using string formatting.
You could always add a statement like:
foo.ToString(format)
if (string.IsNullOrEmpty(foo))
foo = "0";
try this:
string format = "0." + new string('#', 324);
It will add zero before dot (if needed)
See example ideone
Maybe it's what you are looking for:
double aa = 12.33333;
string foo = String.Format("{0:0.#}", System.Convert.ToSingle(aa));
Argh, those hacks people use. To give one hack more here:
foo.ToString(format + ";" + "-" + format + ";" + "0");
or with
static readonly string newFormat = format + ";" + "-" + format + ";" + "0";
defined under format in the code source, just:
foo.ToString(newFormat);
Of course that is a constant, so it is really:
foo.ToString(.####################################################################################################################################################################################################################################################################################################################################;-.####################################################################################################################################################################################################################################################################################################################################;0);
Hope you like it (I don't).

How do I create a file based on the date?

string filename = DateTime.Today.ToString() + ".csv";
if(!File.Exists(filename))
File.Create(filename);
I thought this would work but it throws a 'format not supported' error. I just want a csv to be created in the directory alongside my .exe
I think the problem is that converting a DateTime to a string will generate a string with invalid filename characters, such as colons (:) and that will cause the create to fail.
You may want to use a format string to control the generated filename. e.g.
string filename = DateTime.Today.ToString("yyyy-MM-dd") + ".csv";
This is because DateTime.Today.ToString() contains slashes, which are not valid as part of a windows filename.
You can, however, do this: DateTime.Now.ToString("yyyyMMdd")
I'm guessing your locale has / / : (or similar confusing characters) in the date format. You should specify an explicit format - "yyyy MM dd" for example:
string filename = DateTime.Today.ToString("yyyy MM dd",
CultureInfo.InvariantCulture) + ".csv";
As everybody has pointed out, the default DateTime.ToString() formatting has invalid characters in it (for just about any region settings), so that
string filename = DateTime.Now.ToString() + ".csv";
generates a 'filename' like 2/18/2011 4:26:48 PM.csv -- which is invalid
if you want a date-time based name, try
string filename = DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";
to get something like 2011021804254.csv
you can add more formatting, just as long as it doesn't contain any of the following: \ / : * ? " < > |
Your date has slashes in it, try this instead
string filename = Datetime.Now.Ticks.ToString() + ".csv";

Categories

Resources