I have the following string:
"23/09/2015 08:00\r\n עד\r\n24/09/2015 08:00"
As you can see, we have two dates. One before the first \r\n and the other one after the second \r\n.
How can I retrieve DateTime objects from this string in C#? The only way I know is to use Substring but that retrieves the text after the first \r\n.
This may help
var stringValue = "23/09/2015 08:00\r\n עד\r\n24/09/2015 08:00";
var splitted = stringValue.Split(new string[]{"\r\n"},StringSplitOptions.RemoveEmptyEntries);
var firstStringDate = splitted[0];
var secondStringDate = splitted[2];
And to get the DateTime:
var firstDate = DateTime.ParseExact(splitted[0], "dd/MM/yyyy HH:mm", DateTimeFormatInfo.InvariantInfo);
var secondDate = DateTime.ParseExact(splitted[2], "dd/MM/yyyy HH:mm", DateTimeFormatInfo.InvariantInfo);
Split and TryParse the strings:
static IEnumerable<DateTime> extractDates(string inputString)
{
foreach (var item in inputString.Split(new string[] {"\r\n"}, StringSplitOptions.RemoveEmptyEntries))
{
DateTime dt;
if(DateTime.TryParseExact(item,
"dd/MM/yyyy HH:mm",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out dt))
yield return dt;
}
}
I would use myString.Split("\r\n") like so:
string[] dates = myString.Split("\r\n");
foreach (var dateString in dates)
{
DateTime dateTime;
if (DateTime.TryParse(dateString, out dateTime))
{
//Use dateTime here
}
}
Related
How can I convert this string to a DateTime:
string t = "2017-02-20 13h24m18s";
The format is: XXXX-XX-XX XXhXXmXXs
You could use DateTime.TryParseExact to parse the string using a specific format:
string t = "2017-02-20 13h24m18s";
if(DateTime.TryParseExact(t, #"yyyy-MM-dd HH\hmm\mss\s", CultureInfo.InvariantCulture,
DateTimeStyles.None, out var dt))
{
// parsed successfully into dt
}
Just be sure to escape 13h as HH\h, 24m as mm\m and 18s as ss\s.
You can replace values easily before converting
static public DateTime todate(string t)
{
t = t.Replace("h", ":");
t = t.Replace("m", ":");
t = t.Replace("s", "");
return DateTime.Parse(t);
}
now use
string test = "2017-02-20 13h2m18s";
DateTime a = todate(test);
Quick Question
Value passed in ActivationDate or ExpirationDate string, must be in either of the two formats stated below:Format 1:YYYY-MM-DD & Format 2: YYYY-MM-DD HH:MM
If the date values are not in either of the above format, then it should report back appropriate error message.
Any clue? Thanks in advance
You can use DateTime.TryParseExact, using a string[] with the valid formats:
string[] formats = new string[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm" };
string s = "2017-12-01 12:23";
DateTime date;
bool converted = DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
With this code, you get in convertedif the input date was in a valid format, and in date the parsed DateTime
You can use ParseExact() with try-catch:
string date = "2017-02-01";
DateTime dt = default(DateTime);
try
{
dt = DateTime.ParseExact(date, new string[] {"yyyy-MM-dd", "yyyy-MM-dd hh:mm"}, CultureInfo.InvariantCulture, DateTimeStyles.None);
}
catch (FormatException ex)
{
//error
}
OR
Use TryParseExact():
string date = "2017-02-01";
DateTime dt;
if (DateTime.TryParseExact(date, new string[] {"yyyy-MM-dd", "yyyy-MM-DD hh:mm"}, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
//do something and use "dt" variable
}
else
{
//error
}
I've got a string that contains a value of datetime:
string myStr = "= '2015-12-01 00:00:00.000'";
How can I check if myStr contains a datetime value?
How can I get only the datetime value from myStr? The datetime value got from myStr should be: "2015-12-01 00:00:00.000".
The sample code that I have tried to do the task:
string myStr = "= '2015-12-01 00:00:00.000'";
Regex rgx = new Regex(#"\d{2}-\d{2}-\d{4}");
Match mat = rgx.Match(myStr);
if (mat.ToString() != "") //This will check if string contains datetime value
{
DateTime myDateTime = DateTime.Parse(mat.ToString()); //This will get the datetime value from string
}
Note: The result from the sample code above is: It can't check if myStr contains a datetime value. It can't get the datetime value from myStr.
You could help me to check if a string contains a datetime value, and get the datetime value within a string.
Try this
var myStr = "= '2015-12-01 00:00:00.000'";
var match = Regex.Matches(myStr, #"'(.*?)'")[0].Groups[1].Value;
DateTime result;
if (DateTime.TryParse(match.ToString(), out result)) {
// Your string has a valid DateTime and it is parsed in result
}
else {
// Invalid
}
There are two things we need to do:
Write a regex which get things that look like they might be a date. However, since dates can be exceedingly complex, we want to delegate that validation to the built-in DateTime library.
For each possible match, we want to validate that it's actually a date.
private IEnumerable<DateTime> GetDates(string str)
{
var dateSearcherRegex = new Regex(#"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d{3}");
foreach (Match match in dateSearcherRegex.Matches(str))
{
var matchedString = match.Groups[0].Value;
DateTime date;
if (DateTime.TryParseExact(matchedString, "yyyy-MM-dd hh:mm:ss.fff", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
yield return date;
}
}
}
And using it like this:
string myStr = "= '2015-12-01 00:00:00.000'";
var dates = GetDates(myStr);
string myStr = "= '2015-12-01 00:00:00.000'";
DateTime dt;
bool b = DateTime.TryParse(myStr.Split(' ')[1].Replace("'",string.Empty),out dt);
if (b)
{
Console.WriteLine("contains datetime");
}
else
{
Console.WriteLine("doesn't contain datetime");
}
Use TryParse function to check for DateTime values
If you still want using regex to parse the date:
Regex rgx = new Regex(#"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d{3}");
Match result = rgx.Match(myStr);
if (mat.Success)
{
DateTime myDateTime = DateTime.ParseExact(m.Value, "yyyy-MM-dd hh:mm:ss.fff", CultureInfo.InvariantCulture);
}
CMIIW.
I really cannot make sense of why this does not want to work. I get an exception:
String was not recognized as a valid DateTime.
I am reading the string date from a file and looks like this 2/27/2014 10:10:55
This method receives the filename and extrapolates the data I need (latitude, longitude, date)
public void ReadCsvFile(string filename)
{
var reader = new StreamReader(File.OpenRead(filename));
gpsDataList = new List<GpsFileClass>();
while(!reader.EndOfStream){
var line = reader.ReadLine();
var values = line.Split(',');
if(values[2].Contains("A")){
values[2] = values[2].Substring(0,values[2].IndexOf("A"));
values[2].Replace("\"", "");
values[2] = values[2].Trim();
}
if(values[2].Contains("P")){
values[2] = values[2].Substring(0, values[2].IndexOf("P"));
values[2].Replace("\"", "");
values[2] = values[2].Trim();
}
gpsDataList.Add(new GpsFileClass(Convert.ToDouble(values[0]), Convert.ToDouble(values[1]), Convert.ToString(values[2])));
}
}
Once the I have the file data in a List<> I want to do some date comparisons and calculations. But first; I try to convert the string data containing date information to datetime like this:
public void SaveFrameGpsCoordinate()
{
int listSize = gpsDataList.Count;
DateTimeFormatInfo dateTimeFormatInfo = new DateTimeFormatInfo();
dateTimeFormatInfo.ShortDatePattern = "dd-MM-yyyy HH:mm:ss";
dateTimeFormatInfo.DateSeparator = "/";
//DateTime tempDateA = DateTime.ParseExact(gpsDataList[0].timeCaptured, "dd/MM/yyyy HH:mm:ss",null);
//DateTime tempDateB = DateTime.ParseExact(gpsDataList[lastRecordData].timeCaptured, "dd/MM/yyyy HH:mm:ss", null);
DateTime tempDateA = Convert.ToDateTime(gpsDataList[0].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
DateTime tempDateB = Convert.ToDateTime(gpsDataList[lastRecordData].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
}
As you can see even ParseExact throws the same exception, I tried it (hence commented it out).
There are a lot solutions for this kind of problem but non seem to work on mine. I get that DateTime by default uses en-US calture. But When I even when I change the culture to "af-ZA" I get the same exception.
Please help.
I don't believe it; The variable that holds the size of the List<> was going out of range (check line 3 of code below) but for some reason it did not throw an "out of range exception".
public void SaveFrameGpsCoordinate()
{
int listSize = gpsDataList.Count - 1;
DateTimeFormatInfo dateTimeFormatInfo = new DateTimeFormatInfo();
dateTimeFormatInfo.ShortDatePattern = "dd-MM-yyyy HH:mm:ss";
dateTimeFormatInfo.DateSeparator = "/";
//DateTime tempDateA = DateTime.ParseExact(gpsDataList[0].timeCaptured, "dd/MM/yyyy HH:mm:ss",null);
//DateTime tempDateB = DateTime.ParseExact(gpsDataList[lastRecordData].timeCaptured, "dd/MM/yyyy HH:mm:ss", null);
DateTime tempDateA = Convert.ToDateTime(gpsDataList[0].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
DateTime tempDateB = Convert.ToDateTime(gpsDataList[lastRecordData].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
}
You can use the ParseExact method
var dateTime = DateTime.ParseExact("2/27/2014 10:10:55",
"M/d/yyyy h:m:s", CultureInfo.InvariantCulture);
'dd' expects a 2 digit date. You probably want to use 'd' instead.
Similarly 'MM' expects a 2 digit month - again you probably want to use 'M' instead.
Source: http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
I am trying to create a textbox that will translate 1225 to 12/25/13. After having done a lot of research, I think "DateTime.TryParseExact" is what I need to use, but I can't get it to work. Here is my code:
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime dateValue;
string[] DateTimeFormats = new string[]{
"MM/dd/yy","MM/dd/yy HH:mm","MM/dd/yy HH:mm:ss","HH:mm","HH:mm:ss",
"M/d/yy","M/d/yy HH:mm","M/d/yy HH:mm:ss",
"MM/dd/yyyy","MM/dd/yyyy HH:mm","MM/dd/yyyy HH:mm:ss",
"MMddyy","MMddyyHHmm","MMddyyHHmmss","HHmm","HHmmss",
"MMddyyyy","MMddyyyyHHmm","MMddyyyyHHmmss",
"MMddyy HHmm","MMddyy HHmmss",
"MMddyyyy HHmm","MMddyyyy HHmmss",
"yyyyMMdd","yyyyMMddHHmm","yyyyMMddHHmmss"};
if (DateTime.TryParseExact(TheTextBox.Text, DateTimeFormats, provider, DateTimeStyles.None, out dateValue))
{
TheTextBox.Text = dateValue.ToString("d MMMM yyyy");
}
Any ideas how to fix this?
If it is possible to predict all possible formats, then you can try something like this
static void Main(string[] args)
{
CultureInfo enUS = new CultureInfo("en-US");
string dateString;
DateTime dateValue;
dateString = "0501";
var dateFormats = new String[] {"MM/dd/yy","MM/dd/yy HH:mm","MM/dd/yy HH:mm:ss","HH:mm","HH:mm:ss",
"M/d/yy","M/d/yy HH:mm","M/d/yy HH:mm:ss",
"MM/dd/yyyy","MM/dd/yyyy HH:mm","MM/dd/yyyy HH:mm:ss",
"MMddyy","MMddyyHHmm","MMddyyHHmmss","HHmm","HHmmss",
"MMddyyyy","MMddyyyyHHmm","MMddyyyyHHmmss",
"MMddyy HHmm","MMddyy HHmmss",
"MMddyyyy HHmm","MMddyyyy HHmmss",
"yyyyMMdd","yyyyMMddHHmm","yyyyMMddHHmmss", "MMdd"};
bool matchFound = false;
foreach (var dateFormat in dateFormats)
{
if (DateTime.TryParseExact(dateString, dateFormat, enUS, DateTimeStyles.None, out dateValue))
{
matchFound = true;
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue.ToString("dd MM yyyy"), dateValue.Kind);
}
}
if (!matchFound)
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
Console.ReadKey();
}
For the example you provided consider the following change to your code...
string[] DateTimeFormats = new string[]{"MMdd"};
You can use DateTime.ParseExact to translate your string into a DateTime:
The text of the textBox1 is 1225:
DateTime date = DateTime.ParseExact(textBox1.Text,"MMdd",CultureInfo.InvariantCulture);
string yourDate = date.ToString("MM/dd/yy"));
//yourDate is 12/25/13
Note: This will always return the date with the current year (here: 2013).