Update Path Automatically at date change ? - c#

my program is watching a text file log - generated each day automatically.
now when the day change my program keep using the last day file path,
is there a way to do so without checking that the datetime.day each time and equal it to the day when the app launched at?
i saw SystemsEvent.TimeChanged but it only work when the user change the date manualy,
thanks.

The simple way to do this is make your path using a DateTime object. For example;
string fp = #".\subdir\otherSubdir\somefile-" + DateTime.Now.ToString("MM-dd-yyyy") + ".log";
Of course I don't know what the format of your date is. Docs on format specifiers for DateTime's ToString method can be found here; http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
As pointed out in the comments you could also use a FileSystemWatcher however, that is quite a bit more complicated and likely unnecessary here. If you're looking for a more general solution (something that could work with files that use different naming conventions) that would be the way to go.

Related

DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss") gives different formats for different users

I assumed that ToString("yyyy/MM/dd HH:mm:ss") will force the string to be formatted with '/', but I can see that every device gets different formats. How can I force it to be saved with '/'?
Good example-
2021/10/06 18:05:53
Strange examples I see in my DB from different users-
2021-10-06 23:48:37
2021.10.12 12:41:42
2021. 10. 06 19:17:23 ('.'+ space after)
2021.10.13 19.18.16
One solution is to replace every -, . and . to /, but this only solves the strange examples I found. What if there are others?
/ in a format string means "the culture-specific date separator". If you want the literal forward-slash, quote it (and the colons, to avoid the use of a custom time separator):
ToString("yyyy'/'MM'/'dd HH':'mm':'ss")
Alternatively - and probably better - use the invariant culture. Not only will that use / as the date separator, but you won't need to worry about a culture having a different default calendar. (It'll always use the Gregorian calendar, which is presumably what you want.)
Even better, use an ISO-8601 format - you're already using a "slightly unusual for humans" format of year-first, so you might as well go the whole hog and go with the standard format for dates and times.
Sample code:
String text = dateTimeValue.ToString(
"yyyy-MM-dd'T'HH:mm:ss",
CultureInfo.InvariantCulture);
This is also the sortable standard date/time format so you can simplify the code significantly:
String text = dateTimeValue.ToString("s");
(That format always uses the invariant culture.)
That's if you really need to format the string at all, though. If you're saving it in a database, I'd advise you to:
Use an appropriate type in the database, e.g. DATETIME
Store it using a parameter (specifying the value just as a DateTime), not formatted text
If you do both of these, you'll avoid oddities like this.
Another solution that I can think of is creating a new function that creates a date
DateTime date= DateTime.UtcNow;
And extracting manually and splitting the date to a few strings (year,month,day,hour,month,seconds)
string year = date.Year.ToString(); string month = date.Month.ToString();...
and building a string out of it in the right format,
string newDate= year + "/" + month + "/" + day + " "+ hour+":"+ minute+ ":"+seconds;
that way I can be sure it's always one format that I'll decide on
How about storing the date as a number, eg unix time - DateTimeOffset.UtcNow.ToUnixTimeSeconds() or (DateTime.UtcNow - DateTime.UnixEpoch).TotalSeconds - it's a lot simpler and cheaper to store a number than a string
Also wanted to point out that the only date I've
seen you store so far is UtcNow (as written in your answer) - fire base does appear to have a solution for that in that you can send ServerValue.TIMESTAMP and it will cause fb to store the unix time as the server sees it.
My take away from this (never used fb) is that that's how they store dates so perhaps it makes sense to follow :)

C#: doing math on weird formatted dateTimes

I've got some Date-timestamps reading in from a log file, the problem is that the log file records these timestamps weirdly, for example:
"2020061515141112" is how its in the file, which represents "2020 06/15 15:14:11.12"
The issue I'm running into is that I've got loglines for start events and end events, and I need to parse out time period between them.
My question is:
in a C# application, how can I parse the strings (yyyyMMddHHmmssff) into a format that can be used by DateTime to perform a <DateTime.Subtract> between them? I'm not super familiar with Date-times and having a hard time getting Visual Studio to agree with the below:
DateTime aDT = DateTime.Parse(aLogDate,"yyyyMddHHmmssff",System.Globalization.DateTimeStyles.None);
which meets the expected format of (string,IFormatProvider,DateTimeStyle) but arguments are invalid (is it the format provider?)
EDIT: we were able to modify the format the Log prints (sort of) to retain leading zeros in their dateTimes, so this is no longer an issue, above still in question)
DateTime aDt = DateTime.ParseExact(aLogDate, "yyyyMMddHHmmssff", System.Globalization.CultureInfo.InvariantCulture);
Help from a friend came first. Heres what I wanted, people were getting to caught up on details, should have made question more concise to begin with

DateTime.Parse can format unusual format strings?

I was looking at a code in an application (Someone else wrote it),on some cases it worked fine and on some cases it gave exceptions,it was actually converting strings in datetime,here is the code
//5000 is the year,but what about "1" is it month or day ?,if its month
//then what about the day ?
DateTime time = DateTime.Parse("1.5000");//1.5000 doesn't looks a date to me ?
time.ToString();//returns "1/1/5000 12:00:00 AM"
//where as if I give this string to DateTime.Parse();
time = DateTime.Parse("2341.70");
//FormatException was unhandled
//String was not recognized as a valid DateTime.
A Confusing thought
How does this string "3.5000" (it matches the 1.5000 pattern) evaluates , does this means 3-3-5000 or 1-3-5000 ,the format is ambiguous its unclear and confusing !
My questions are,
What kind of formats can DateTime.Parse expects ?
Whats happening in the code above ?
Suggestions to improve the code ?
Many people have commented on the possible reasons for the parse that you have seen being successful but your question seems to have several separate parts...
1. What kind of formats can DateTime.Parse expects ?
DateTime.Parse has been written to be as inclusive as possible. Pretty much anything that it can find someway to make into a DateTime it will do its best to do so which means in addition to the usual familiar yyyy-MM-dd type formats more strange ones like M.yyyy or yyyy.M and so on.
2. Whats happening in the code above ?
That is very complicated because the DateTime.Parse method is itself very complicated. You can probably fidn the source code out there somewhere but the complexity made it very hard for me to follow. Without being able to give precise details I'm going to answer this the same as above. What is happening is that the framework is trying its best to give you a date back and not throw an exception. The date it gives is the best guess as to what you meant.
3. Suggestions to improve the code ?
It sounds like if you are getting parse exceptions that you are passing dates in formats that are unexpected. Without knowing what those inputs are its hard to say. Two things could improve your code though. Making sure a single consistent date format is used and then using DateTime.ParseExact to ensure that it conforms to the right format. You will remove all ambiguity this way but you will sacrifice flexibility.
The second option is to use DateTime.TryParse. This will attempt to parse your date and then return a boolean saying whether it succeeded or not. If successful the date parse will be returned in a ref parameter. This won't make your code any better at recognising unknown date formats but will let your code know when such an unparsable format crops up and you can deal with it (eg by providing user feedback reporting the wrong format and suggesting a correct one, or just by logging it or something else).
What the best method is depends mostly on where your input is coming from. If it is user input then I'd go with the second option. If it is automated input then you probably want to make sure your input is standardized and then use the first option. Of course circumstances always vary so this is not a hard and fast rule. :)
In regards to "2. Whats happening in the code above ?":
In some cultures, the date separator is a dot instead of a slash. So for example 13.12.2013 is a valid date (2013-12-13) in the format "dd.MM.yyyy". Now by whatever design choice, the day part in this example is not mandatory and if left out, is automatically filled with 1. So parsing 12.2013 would result in 2013-12-01. And therefore it's easy to see how 1.5000 would become 5000-01-01. 2341.70 can not be parsed, because 2341 is not a valid month. - So in this case 1.5000 is a "valid" date in the format M.yyyy.

Date time day/month (02/12)

This seems like something I should be able to find on Google but I'm not having much look.
I'd like to format a date as day/month. Only thing I've found it {0:M} which displays the information I want however the month written out like December rather than "12". I need to use 02/12 if possible due to space restrictions.
Thanks for any help!
You could try the following format:
{0:dd/MM}
Have you simply tried:
myDateTime.ToString(#"dd/MM");
Are you sure its ignoring your local computer regional settings ?
What happens if you do:
Console.WriteLine(date1.ToString("M", CultureInfo.CreateSpecificCulture("en-US")));

Is there an API to convert from "YYYYMMDDHHMMSS.UUUUUU-TZO" format to C# DateTime?

Example: "20080807144334.410187-180" (-180 means GMT minus three hours. Rio de Janeiro in this case.)
That string format is returned when I query file creation/change/access times via WMI (that is not totally working; see here). I guess I could parse it the idiot way, extracting year, month etc. from the string positions. But I'd like not to reinvent the wheel. System.DateTime's constructors don't handle that format. Should I go on and do it the idiot way or is there something better?
You should be able to use DateTime.ParseExact or .TryParseExact to give it the specific format to use when parsing.
However, I don't think you can get it to read your time zone in that format (though I can't actually figure out how to get it to read a time zone in any format).
The rest of it would look like this:
DateTime.ParseExact("20080807144334.410187", "yyyyMMddHHmmss.ffffff", System.Globalization.CultureInfo.InvariantCulture)
You should take a look at the DateTime.TryParseExact method. It'll let you pass in your format that you're converting from.
http://msdn.microsoft.com/en-us/library/system.datetime.tryparseexact.aspx

Categories