I try to use regular expression to find a date and time from a log file that looks like this:
Dec 25 14:11:03....
what is the best way to find them in log file and calculate the date and time
to an absolute value?
I am trying this code but it doesn't find the expression:
public long getDateAndgetTimeFromLog(TypeOfProtocols type, string lineOfLog)
{
long dnt = 0; //variable from date and time.
switch (type)
{
case TypeOfProtocols.PlinkSnifer:
if (Regex.IsMatch(lineOfLog, #"\d{2}:\d{2}:d{2}"))
{
}
break;
}
return dnt;
}
First: your pattern is invalid:
#"\d{2}:\d{2}:d{2}"
it must be:
#"\d{2}:\d{2}:\d{2}"
you missed one backslash \ before the last d
Second: I guess by absolute value you mean the long dnt variable? If so then you need to parse the date by using one of the overloads and get the DateTime.Ticks.
For example like this:
string dateString = "Dec 25 14:11:03";
DateTime date = DateTime.ParseExact(dateString, "MMM dd HH:mm:ss", CultureInfo.InvariantCulture);
long ticks = date.Ticks;
where:
MMM The abbreviated name of the month.
dd The day of the month, from 01 through 31.
HH The hour, using a 24-hour clock from 00 to 23.
mm The minute, from 00 through 59.
ss The second, from 00 through 59.
Custom Date and Time Format Strings
Third: your current pattern cannot find and capture the entire timestamp so you'll need to extend it to get the date and time parts in one string:
string logLine = "Dec 25 14:11:03 Hello world!";
// Your new pattern:
string pattern = #"([a-z]{3} \d{2} \d{2}:\d{2}:\d{2})";
Match match = Regex.Match(logLine, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
string dateFormat = "MMM dd HH:mm:ss";
string dateString = match.Groups[1].Value;
DateTime date = DateTime.ParseExact(dateString, dateFormat, CultureInfo.InvariantCulture);
long ticks = date.Ticks;
}
Currently you are only checking whether a log line contains a timestamp. I've added a () catching group to the pattern so you can use the cought value match.Groups[1].Value for parsing if a match was found. The index is 1 because there is only one group defined in the pattern. Group at the index 0 always contains the original string (the entire log line in this case).
Related
After reading some other similar questions and trying their suggestions, I'm still unable to get my time to parse into a DateTime-
string time1 = File.ReadAllText(#"C:\Reminders\Reminder1Time.txt");
DateTime dt1 = DateTime.ParseExact(time1, "hh:mm:tt", CultureInfo.InvariantCulture);
dateTimePicker1.Value = dt1;
time1 is a string value of 9:00 AM Other questions have mentioned to use ParseExact to specify a custom format, but it's still not parsing.
The error I get thrown is on the second line
String was not recognized as a valid DateTime.
How would I get the dateTimePicker1 to display the value from the time1 string?
Looks like a stray colon and an extra h if you are expecting a 12 hour clock 1-12 without a leading zero and the AM PM marker with whitespace.
Try: h:mm tt
All of the formatting options are buried in the documentation, here.
var datefromFile = File.ReadAllText(FILELOCATION);
var format = "dd-MM-yyy hh:mm:ss,fff";
var formattedDateTime = DateTime.ParseExact(dateFromFile, format, CultureInfo.InvariantCulture);
Make your format Explicit, remember dd for date capital MM for month and yyyy for year. hh for hour mm for minutes and ss for seconds.
MSDN Formats:
https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
I'm trying to Split this string: 2015-08-14 20:30:00
but the compiler shows this message:
Can't convert from String to Char
This is my code:
string date = reader["date"].ToString().Split("-").ToString();
The variable reader["date"] is an object, so I must convert it into a String. I want to Split the content into three other variable like this:
year: 2015
month: 08
day: 14
What am I doing wrong?
There is no String.Split overload that takes string as a parameter. That's why it looks closest overload which is char[] but there is no implicit conversation between them.
var array = "2015-08-14 20:30:00".Split(new char[]{'-', ' '});
will return
and you can get them with array[0], array[1] and array[2].
Also you can use to parse your string to DateTime instead (which your string is valid one) of splitting it like;
string s = "2015-08-14 20:30:00";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// dt.Year;
// dt.Month;
// dy.Day;
}
But since these properties are int, you will not get leading zeros for your single digit month and days.
In such a case, you can choose to use dd and MM custom date and time format specifiers.
Sometime a different approach should be considered. If your reader field datatype is date or datetime then using the correct datatype is the correct way to handle this info. A DateTime has already all you need.
DateTime dt = Convert.ToDateTime(reader["date"]);
int year = dt.Year;
int month = dt.Month;
int day = dt.Day;
As String.Split reaturns an array of strings you need date to be the same. So simply write
string[] date = Convert.ToString(reader["date"]).Split("-");
I'm having trouble to remove the leading zero from a date I found this on the miscrosoft website.
DateTime date1 = new DateTime(2008, 8, 18);
Console.WriteLine(date1.ToString("(M) MMM, MMMM",
CultureInfo.CreateSpecificCulture("en-US")));
// Displays (8) Aug, August
Totally doesn't work here.
This is my code:
string date = '2013-04-01'
DateTime billrunDate = Convert.ToDateTime(date);
string test = billrunDate.ToString("M");
Test is now 01 April
I just need it to be 4 in a string or int idc
Thanks!
Edit if I do:
billrunDate.ToString("(M)");
I get (4), but I dont need ()
EDIT 2:
Well this works
string test = billrunDate.ToString(" M ");
string testTwo = test.Trim();
Very very ugly
It's interpreting M as a standard date and time format for "month day pattern".
To interpret a single character pattern as a custom date and time pattern, just prefix it with %:
string test = billrunDate.ToString("%M");
One of my most referenced MSDN pages is the Custom Date & Time Format Strings page. You can use these as part of the formatting passed in to the ToString() method. If any of them are standard formatting patterns (as "M" is) and you want to use them along, you have to preface them with '%' or have a space before or after them in the format string (so use "%M", " M", or "M " instead of "M").
Relevant section:
"M"
The month, from 1 through 12.
"MM"
The month, from 01 through 12.
"MMM"
The abbreviated name of the month.
"MMMM"
The full name of the month.
You don't need to convert to string the date to retrieve the month number.
Just read the Month property of the DateTime class:
string date = "2013-04-01";
DateTime billrunDate = Convert.ToDateTime(date);
string test = billrunDate.Month.ToString();
I know about Datetime formats. "dd" stands for day from 01 to 31, "MM" - the month from 01 through 12. I need this format. But if I write "dd MM"(in my case in ToString() method) it will always put day before the month. How can I set this format(dd and MM) without changing the order(what comes first - day or month) from current locale? So if in current culture day comes first I want to receive "20 08 2012"(separator doesn't matter here), and if month comes first - "08 20 2012"
You can use the MonthDayPattern from the current locale to get the relative order of the two items, and then construct either dd MM or MM dd:
var mdp = CultureInfo.CurrentCulture.DateTimeFormat.MonthDayPattern;
string pattern = mdp.IndexOf('M') < mdp.IndexOf('d') ? "MM dd" : "dd MM";
Have a look at the culture's MonthDayPattern. Maybe you can customize it to your needs, e.g.
string FormatWithMonthDayPattern(DateTime dateTime, CultureInfo cultureInfo)
{
var pattern = cultureInfo.DateTimeFormat.MonthDayPattern;
return dateTime.ToString(Regex.Replace(pattern, "M+", "MM"));
}
var result1 = FormatWithMonthDayPattern(DateTime.Now, new CultureInfo("en-US"));
// result1 == "08 20"
var result2 = FormatWithMonthDayPattern(DateTime.Now, new CultureInfo("fr-FR"));
// result2 == "20 08"
I'm trying to format some DateTime into this W3C DateTime format :-
Complete date plus hours and minutes:
eg. YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
where:
YYYY = four-digit year
MM = two-digit month (01=January, etc.)
DD = two-digit day of month (01 through 31)
hh = two digits of hour (00 through 23) (am/pm NOT allowed)
mm = two digits of minute (00 through 59)
ss = two digits of second (00 through 59)
s = one or more digits representing a decimal fraction of a second
TZD = time zone designator (Z or +hh:mm or -hh:mm)
I originally had this...
var myDateTime = someDateTime.ToString("s",
System.Globalization.CultureInfo.InvariantCulture);
But that results in a string of :
2011-08-31T08:46:00
Can anyone help?
You want "o":
var myDateTime = someDateTime.ToString("o",
System.Globalization.CultureInfo.InvariantCulture);
Use the following:
yourDateTime.ToString( "yyyy-MM-ddTHH:mmK", CultureInfo.InvariantCulture );
Here is more than you'll ever want to know on DateTime formats:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
I believe you want
"yyyy-MM-ddTHH:mmK"
Note:
HH rather than hh to be 24 hour
K to specify the time zone; this relies on the DateTime.Kind being UTC or local; unspecified will end up with an empty string
You should also use CultureInfo.InvariantCulture to make sure no funky culture information is used. (You could quote the - and : as an alternative, but I'd use the invariant culture to make sure.)
You can format it like this:
someDateTime.ToString("yyyy-MM-dd");
Here's the documentation of the 'standard' supported datetime format strings:
http://msdn.microsoft.com/en-us/library/az4se3k1(v=VS.100).aspx
someDateTime.ToUniversalTime().ToString("u");
Will get you pretty close => '2011-09-02 10:22:48Z'. If that isn't good enough, then you can create a custom format string that includes the "T" (see 'Custom Date and Time Format Strings').