spliting the string - c#

I have an string like this
string strdate =#"5/2/2006";
Which is in a form of month/day/year.
I need to display it in a form of like this 02-05-2006.
How do i format the data like this?
If the value is like this: 12/28/2005, it should be displayed like this: 28-12-2010.
I know we should be splitting the data based on that we should do it.
I am not getting the syntax how to do it .
Any help would be great.

Parse the string into a DateTime and then use ToString with the right format to output it.
DateTime dt = DateTime.ParseExact(#"5/2/2006",
"MM/dd/yyyy",
CultureInfo.InvariantCulture);
string output = dt.ToString("dd-MM-yyyy");
I suggest reading up on custom and standard date and time format strings.

Read about how to parse DateTime string here: http://msdn.microsoft.com/en-us/library/1k1skd40.aspx
Then you read about how to print it here: http://msdn.microsoft.com/en-us/library/8tfzyc64.aspx

#Kevin
var datearray = strdate.split('/');
string date = datearray[0] + "-" + datearray[1] + "-" datearray[2]
Issue 1
This wont work from days from 10th to 31st... It will add leading zero to each day.
12-05-2010 is good, but for ex. 12-021-2010 is not good.
Issue 2
Wrong order of MM-dd

You can use string.replace as such:
string newString = oldString.Replace('/', '-');
This will replace each '/' with '-' and create a new string, it will not replace it within the old string as strings are immutable.

Related

How to Extract datetime value with AM/PM && remember its position from string

I've see
this post. What if my string is string x = "Tomorrow 04-26-19 09:14AM sunrise.";, basically the datetime value is always in mm-dd-yy hh:mm<AM/PM> format. So I'd need to extract this value of 04-26-19 09:14AM and remember the starting position which = 9.
This works nicely for me:
string x = "Tomorrow 04-26-19 09:14AM sunrise.";
var regex = new Regex(#"\d{2}-\d{2}-\d{2} \d{2}:\d{2}(AM|PM)");
var match = regex.Match(x);
if (match.Success)
{
var prefix = x.Substring(0, match.Index);
var value = DateTime.ParseExact(match.Value, "MM-dd-yy hh:mmtt", System.Globalization.CultureInfo.CurrentCulture);
var suffix = x.Substring(match.Index + match.Length);
}
It's using Regex to find a potential DateTime string and then determines the prefix part of the string, the DateTime value, and the suffix part of the string.
It gives me:
"Tomorrow "
2019/04/26 09:14:00
" sunrise."
If "tomorrow" and "sunshine" aren't necessarily always going to be present in a string like x but the format of this string will be similar, I'd probably split these strings according to the space character like this.
x.Split(' ')
with indices
string strDate = x.Split(' ')[1];
string strTime = x.Split(' ')[2];
& then join those sets of strings
string dt = $"{strDate} {strTime}";
& then probably use the DateTime.ParseExact functionality to craft an actual DateTime object out of what I parsed.
DateTime.ParseExact(dt, "MM-dd-yy hh:mmtt", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeLocal)
I generally use assumelocal so that I know the time won't be UTC.
"tt" is a placeholder for AM or PM.
If this is something you'll have to do iteratively, then I would probably create a method for this, and then simply call it routinely.

Get DateTime from FileName

I have a file named test-2000_01_02-10_12_14.xml.
How do I only get the date from the file?
I was able to get the date if the file has this name: 2000_01_02-10_12_14
with this (b is a StorageFile):
DateTime dateVal;
bool parsed = DateTime.TryParseExact(b.DisplayName,
"yyyy_MM_dd-H_mm_ss",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out dateVal);
I then tried to change yyyy_MM_dd-H_mm_ss to something like this *-yyyy_MM-dd-H-mm_ss but it does not seem to be the solution
There are a boatload of ways to do this, it really rather depends on how regular the naming of your files is - is there always some junk text followed by a hyped, then the year?
Post up another 10 different examples if you want more tailored advice. Here's a way for the one you've posted:
DateTime.TryParseExact(
Path.GetFileNameWithoutExtension(b.DisplayName.Substring(b.DisplayName.IndexOf('-')+1)),
"yyyy_MM_dd-H_mm_ss",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out dateVal
);
This uses Substring with only one argument (no length) to remove everything after the first hyphen up to the end of the string, and GetFileNameWithoutExtension to remove the .xml - this effectively turns anythinghere-2000_01_01-00_00_00.xml into 2000_01_01-00_00_00 ready for parsing
I could also have gone for a .Remove("last index of period") type thing but it does get a bit messy because you have to subtract the start Index of the hyphen etc
MJWill's comment about splitting on hyphen is also a good one - you could split then take the [1] and [2] indexes and join then back together for parsing..
Lastly don't forget that the file itself might have a created date that is already a good candidate for the date of creation rather than the filename (which might be mangled by humans) so long as it hasn't been transmitted somewhere and re-saved. Take a look at the FileInfo.CreationTime property for that - https://learn.microsoft.com/en-us/dotnet/api/system.io.fileinfo?view=netframework-4.8
First, we have to extract (match) the datetime part from a file name:
using System.Text.RegularExpressions;
...
// Aggravated task: dots and minuses within file's name
string source = #"bla-bla-bla-test.me-2000_01_02-10_12_14.xml";
string datetime = Regex.Match(
Path.GetFileNameWithoutExtension(source),
"[0-9]{4}_[0-9]{2}_[0-9]{2}-[0-9]{2}_[0-9]{2}_[0-9]{2}$").Value;
Then we can parse it
if (DateTime.TryParseExact(
datetime,
"yyyy_MM_dd-H_m_s",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal,
out DateTime result) {
// result is the parsed date
}
else {
// File doesn't contain valid date and time
}
I would suggest you to use regular expression assuming that your file name will be always following the same format you can do something like this:
var pattern = #"\d{4}_\d{2}_\d{2}-\d{2}_\d{2}_\d{2}";
var fileName = "test-2000_01_02-10_12_14.xml";
var match = new Regex(pattern);
var result = match.Match(fileName);
if (result.Success)
{
DateTime.TryParseExact(result.Value,
"yyyy_MM_dd-HH_mm_ss",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out DateTime dateVal);
}

C# - Extract Date from String using StreamReader

How would I go about getting just the date from the following string?
"DateOfTest_01-30-2018-1_003"
This string is in position 8 in a CSV file, which I am looping through and parsing. What I have is:
while (!reader.EndOfStream) {
var splitLine = reader.ReadLine().SplitCommaSeparatedValues();
sample.RunDate = splitLine[8];
WriteLog("Run Date = " + sample.RunDate);}
So I need to extract characters from the string that fall between "_" and "-1" and convert the result to /mm/dd/yyyy format.
Thanks in advance for any assistance!
Better will be regular expression in this case: "(DateOfTest_)(\d{2}-\d{2}-\d{4})(-\d_\d{3})". Second group will be date. In c# you can use Regex.Match. MSDN
Use DateTime.ParseExact:
var culture = System.Globalization.CultureInfo.InvariantCulture;
var strToParse = splitLine[8].Substring(11, 10);
var date = DateTime.ParseExact(strToParse, "MM-dd-yyyy", culture);
var formattedStr = date.ToString("MM/dd/yyyy", culture);
You could use Regex matching to determine date string in the input.
var pattern = #"(?<=_)(.*?)(?=-1)";
var input = "DateOfTest_01-30-2018-1_003";
if (Regex.IsMatch(input, pattern))
{
var dateStr = Regex.Match(input, pattern);
var date = DateTime.ParseExact(dateStr.Value, "MM-dd-yyyy",null);
}
Unless you absolutely need the data at just that exact moment move your date parser outside of your reader.
After that, the answer really relies on whether or not the string in that field is always formatted the same way.
As others have pointed out, if the string is always of the same format you can substring the date out of the string. Then you can either do use one of the several built-in date format methods, or since it is formatted correctly, do a string.Replace("-", "//")
If the string format changes you'll need to try some regex to help you identify the substring to pull out.
My biggest point is that I think you should do this formatting of your field outside of your reader.
string TestString = "DateOfTest_01-30-2018-1_003";
Regex TestRegex = new Regex(#"(DateOfTest_)(\d{2}-\d{2}-20\d{2})(-\d_\d{3})");
string ExactDateFormat = "MM-dd-yyyy";
if (TestRegex.IsMatch(TestString))
{
Date = TestRegex.Match(TestString).Groups[2].ToString();
Date = DateTime.ParseExact(Date, ExactDateFormat, null).ToShortDateString();
}

parsing a string into int/long using custom format strings

In C#.Net, here's a simple example of how to format numbers into strings using custom format strings:
(example taken from: http://www.csharp-examples.net/string-format-int/)
String.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456"
String.Format("{0:##-####-####}", 8958712551); // "89-5871-2551"
Is there a way to convert this formatted string back into a long/integer ? Is there someway to do this :
long PhoneNumber = Int32.Parse("89-5871-2551", "{0:##-####-####}");
I saw that DateTime has a method ParseExact which can do this work well. But I did not see any such thing for int/long/decimal/double.
You can regex out all of the non numeric numbers, and what you're left with is a string of numbers that you can parse.
var myPhoneNumber = "89-5871-2551";
var strippedPhoneNumber = Regex.Replace(myPhoneNumber, #"[^\d]", "");
int intRepresentation;
if (Int32.TryParse(strippedPhoneNumber, out intRepresentation))
{
// It was assigned, intRepresentation = 8958712551
// now you can use intRepresentation.
} else {
// It was not assigned, intRepresentation is still null.
}
Well, you can always do
long PhoneNumber = Int32.Parse("89-5871-2551".
Replace(new char[]{'-','+',whatever..}).Trim());
By the way, considering that you're parsing a string received from some IO, I would suggest to use more secure (in terms of conversion) Int32.TryParse method.
The way like you described doesn't actually exist.
Just Regex out all of the non-numeric characters, then parse that string.

formatting string in C#?

I've a predefined string format. For instance '>>>,>>>,>>9.99' this means that the system should display string in this '500,000,000.10'. The format can change based on the users using it. How can I write a common function to display stings on the given format passing
the input value and the format as the parameter using C#
You can use the ToString method with a standard or custom format string
For example:
string format = "{0:000,000,000.00}";
string val = 12.3456;
Console.WriteLine(string.Format(format, value)); // it prints "000,000,123.23"
You can read more about formating values here http://www.csharp-examples.net/string-format-double/
decimal value = 1.2345;
string rounded = value.ToString("d2");
private string sDecimalFormat = "0.00";
decimal d = 120M;
txtText.Text = d.ToString(sDecimalFormat);
You could then have a setting for decimal format eg:
txtText.Text = d.ToString(Settings.DecimalFormat);
String.formate can be used for formating.
Go there if you want examples
http://www.csharp-examples.net/string-format-double/
I think the following might work:
String result = String.Format(fmt.Replace('>', '#').Replace('9', '0'), inpString);
fmt being the format you want to use and inpString being the string entered by the user.
Just replace the > with # and the 9 with 0 and it'll be a valid .Net formatstring.
There is a Format method on String.
String.Format("{0:X}", 10); // prints A (hex 10)
There are several methods to format numbers, date...
I dont seem to understand how you can make 500,000,000.10 from >>>,>>>,>>9.99' but I believe the answer would be
But I assume something you are looking for is: string.Format("500,000,00{0:0.##}", 9.9915)
You can then make a method like
Public string GetString(string Format, object value)
{
return string.Format(Format, value);
}
Something like this?

Categories