c# split with some delimeters - c#

I have a string like "1392/02/10 22:30:15", how can I separate each number in a variable with split? my code is in the following:
string str1="1392/02/10 22:30:15";
string[] str2 = str1.Split(new char[] { '/', ':',' '});
I got 1392, 02 and 10 but to get 22 by
int hour = int.Parse(str2[3]);
make an execption with this title:"Input string was not in a correct format."

I'd parse the date
string input = "1392/02/10 22:30:15";
string format = "yyyy'/'MM'/'dd HH:mm:ss";
DateTime result = DateTime.ParseExact(input, format, System.Globalization.CultureInfo.InvariantCulture);
int hour = result.Hour;
Fiddle: https://dotnetfiddle.net/489Ev3

It would make much more sense if you'd just parse the date as a DateTime:
string str1 = "1392/02/10 22:30:15";
DateTime d = DateTime.ParseExact(str1, "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture);
If you are not sure about the validness of your input, you can use TryParseExact:
if (DateTime.TryParseExact(str1, "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime d))
{
// the date is valid, use it
}
Your current code works, but is quite error prone. You better rely on pieces of the framework that automate this task. One problem with your code could be an extra space, a tab instead of a space, etc.

Related

Tryparse not working for me and ParseExact works but it fails when extra space is included

Tryparse not working for me and ParseExact works but it fails when extra space is included:
//Tryparse
string dateTimeString = "Sep 10 08:19";
DateTime dateAndTime;
if (DateTime.TryParse(dateTimeString, out dateAndTime))
{
string temp = dateAndTime.ToString(); //"9/21/2018 10:08:00 AM" ??????? why?
}
//ParseExact works fine but it won't work with extra spaces in the date
string format = "MMM d HH:mm";
//dateTimeString = "Sep 10 08:19"; //works fine with this string
dateTimeString = "Sep 9 08:19"; //notice extra extra space between "Sep" and "9"
dateAndTime = DateTime.ParseExact(dateTimeString, format, System.Globalization.CultureInfo.InvariantCulture); //Exception here
string temp2 = dateAndTime.ToString();
Any ideas? Thanks
So first thing is you should use TryParseExact() instead of ParseExact() since that is the right comparable method to TryParse().
Next you just need to pass in an extra parameter to your method, The DateTimeStyles value DateTimeStyles.AllowWhiteSpaces:
if(DateTime.TryParseExact(
"Sep 10 08:19",
"MMM d HH:mm",
CultureInfo.InvariantCulture,
DateTimeStyles.AllowWhiteSpaces,
out dateAndTime))
{
//Parsed correctly, do something
}
Fiddle here

DateTime TryParseExact and padding

I'm calling TryParse on a string that I want to parse as a DateTime. Simple stuff. And it all works when the format is as I'd expect. But when each component/some of the components of the date are a single figure, the parse fails.
Example:
var dateFormat = "yyyy-dd-MM hh:mm:ss";
var dateString = "2006-4-1 2:3:5";
DateTime.TryParseExact(dateString, dateFormat,
CultureInfo.InvariantCulture, DateTimeStyles.None, out result)
If I change my dateString to "2006-04-01 02:03:05", it parses fine.
Question
How can I tell the parser to interpret 2 as 02 so that the above parses successfully?
What I've Tried
Manually padding each part of the date time to ensure it fits the format. This works, but it doesn't feel very elegant. Is this the only way?
I've also tried, with no success, to use a format like m instead of mm.
Just use
// please note single letters (d, M, h, m, s) whenever you allow single digits
var dateFormat = "yyyy-d-M h:m:s";
And you'll get it:
var dateString = "2006-4-1 2:3:5";
DateTime.TryParseExact(dateString, dateFormat,
CultureInfo.InvariantCulture, DateTimeStyles.None, out result)
With regular expression:
int[] n = new Regex("[^0-9]+").Split("2006-4-1 2:3:5").Select(int.Parse).ToArray();
var datetime = new DateTime(n[0], n[1], n[2], n[3], n[4], n[5]);

Reading date from string format

I have to read a date in this format in c#
yyyy/MM/dd HH:mm:ss
I cannot change the format because is written by another application
The date is a string like
2009/11/17 12.31.35
How i can read this format without parsing it(without split if possible)
thanks
I cannot change the format because is written by another application
Solution 1: You don't need to change the format for reading it.
Try This:
DateTime dt;
DateTime.TryParseExact(date, "yyyy/MM/dd HH.mm.ss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
OR
How i can read this format without parsing it(without split if
possible)
Solution 2: If you want to extract the values from the date string.
Try This:
string str = "2009/11/17 12.31.35";
string year = str.Substring(0, 4); //2009
string month = str.Substring(5, 2); //11
string date = str.Substring(8, 2); //17
string Hours = str.Substring(11, 2); //12
string minutes = str.Substring(14, 2);//31
string seconds = str.Substring(17, 2);//35
Use DateTime.ParseExact, where you can supply your custom date format
Try replacing . with : an then ParseExtract
string dt= "2009/11/17 12.31.35";
var dt2= ss.Replace('.', ':');
DateTime d = DateTime.ParseExact(dt2, "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture);
or just
DateTime d = DateTime.ParseExact("2009/11/17 12.31.35", "yyyy/MM/dd HH.mm.ss", CultureInfo.InvariantCulture);

How to know if time part was present when parsing with DateTime

Say, I have two strings containing date/time in arbitrary user-provided format for an arbitrary culture:
string str1 = "6/19/2013";
string str2 = "6/19/2013 1 am";
I can parse them by doing:
DateTime dt1 = DateTime.Parse(str1);
DateTime dt2 = DateTime.Parse(str2);
But how do I know if the time part was present & parsed into the DateTime object?
What do you guys think about something like this?
public static DateTime ParseDateTimeWithTimeDifferentiation(string str, out bool bOutTimePresent)
{
//Parse date/time from 'str'
//'bOutTimePresent' = receives 'true' if time part was present
DateTime dtRes;
//Get formats for the current culture
DateTimeFormatInfo dtfi = CultureInfo.CurrentUICulture.DateTimeFormat;
DateTimeStyles dts = DateTimeStyles.AllowWhiteSpaces |
DateTimeStyles.AssumeLocal;
//Get all formats
string[] arrFmts = dtfi.GetAllDateTimePatterns();
foreach (string strFmt in arrFmts)
{
if (DateTime.TryParseExact(str, strFmt, CultureInfo.InvariantCulture, dts, out dtRes))
{
//Parsed it!
//These format codes come from here:
// http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
bOutTimePresent = strFmt.IndexOfAny(new char[] { 'H', 'h', 'm', 's', 'f', 'F', 't', 'z' }) != -1;
return dtRes;
}
}
//As a fall-back, just parse it as-is
dtRes = DateTime.Parse(str);
//Assume it has time, as otherwise we'd catch the date-only above
bOutTimePresent = true;
return dtRes;
}
You can try using two separate calls to DateTime.ParseExact or DateTime.TryParseExact. This will be especially easy if you know the format of the date and time parts. The code would look something like this:
DateTime dateValue;
var culture = new CultureInfo("en-US");
if (DateTime.TryParseExact(dateString, "M/d/yyyy H:mm:ss", culture,
DateTimeStyles.None, out dateValue))) {
//Using date and time. dateValue var is set.
}
else if (DateTime.TryParseExact(dateString, "M/d/yyyy", culture,
DateTimeStyles.None, out dateValue))) {
//Using just date. dateValue var is set.
}
If you cannot anticipate the exact format of the date/time string, you can either enumerate a bunch of possible possible formats, or use regular expressions to try to extract the time part. Read more about custom date and time formats here. There are also some provided standard date and time formats.
If no time was specified in the string that was parsed, the TimeOfDay property of the DateTime object will be set to midnight (00:00:00). You can then check if that's the case with something like this:
if (dt1.TimeOfDay.Equals(new TimeSpan(0,0,0))) {
//do something
} else {
//do something else
}
EDIT: Another approach could be to separate the date and time sections of the string. This is assuming some type of numerical date format is passed using dashes, commas, or anything besides spaces.
string[] dateString = str1.Split(' ');
string[] date2String = str2.Split(' ');
You'll now have a string array that can be easily used to check for special values. dateString[0], for example, should contain your entire date. dateString[1] and beyond will have any time formats, and can be recombined and parsed into a TimeSpan object. Obviously if you have only a single entity in the array, they've not entered any time.

For valid DateTime(Error shows string was not recognized )

I am trying to convert my string formated value to date type with format dd/MM/yyyy. It runs fine but when I enter fromdate(dd/MM/yyyy) in textbox its fine and todate(dd/MM/yyyy) in textbox then it gives an error that string was not recognized as a valid datetime.What is the problem exactly i dont know. same code run on another appliction its run fine but in my application it shows Error.
Below I have used array for required format and split also used.
string fromdate = punchin.ToString();
string[] arrfromdate = fromdate.Split('/');
fromdate = arrfromdate[1].ToString() + "/" + arrfromdate[0].ToString() + "/" + arrfromdate[2].ToString();
DateTime d1 = DateTime.Parse(fromdate.ToString());
try with DateTime.TryParseExact as below
DateTime date;
if (DateTime.TryParseExact(inputText, "MM/dd/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date))
{
// Success
}
if you know the format of input date time you don't need to do any string manipulation.
But you need to give correct Date and Time Format String
I got 5/13/2013 12:21:35 PM in string fromdate
Use DateTime.TryParseExact, You don't have to split your string based on / and then get first three items from the array instead you can simply do:
DateTime dt;
if (DateTime.TryParseExact("5/13/2013 12:21:35 PM",
"M/d/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
//date is fine
}
Using single d and single M as it can accomodate single digit as well as double digits day/Month part. You can simply pass punchin as the string parameter, Calling ToString on string types is redundant.
Try :
DateTime.ParseExact(fromdate, "MM/dd/yy", CultureInfo.InvariantCulture)
Obviously you can reformat the above, and use different providers by creating an instance of CultureInfo related to the string you are parsing, and you can modify the format string to reflect that culture or to accommodate more date parts

Categories