Parse String to Datetime - c#

Is there a equivalent on .net of the string parsing of Datejs ( http://www.datejs.com/ ) ?
I wanna do things like
// Convert text into Date
Date.parse(‘today’);
Date.parse(‘t + 5 d’); // today + 5 days
Date.parse(‘next thursday’);
Date.parse(‘February 20th 1973′);
Date.parse(‘Thu, 1 July 2004 22:30:00′);
Tks!

The closest thing in the framwork is DateTime.Parse and DateTime.TryParse. Unfortunately, these will only handle your last 2 cases, but the first 3 will not work.
There is no built-in way to do date manipulations using the standard DateTime parsing methods. However, this answer to a different question provides a utility class which will handle some of your other cases (or something similar), using regular expressions.

As Reed mentions, there is nothing like this built into the .Net framework.
Microsoft JScript is a .Net language that can be used for server-side processing; you might look into seeing if you can integrate Datejs that way.

Related

How to use string format to omit period but leave digits

I have the format string ######.00 used for formatting decimals in C#. I need to change it so that it omits the period but keeps the digits following the period. Can I accomplish this just by changing the format? I've searched, but haven't been able to find a solution online.
I found this answer to a very similar question, but it involves multiplying the decimal by 100 before formatting it. I'm not able to manipulate the number going in, nor the resulting string because I don't have access to them. This is because we're using a function from a third-party library that fetches the number from elsewhere and displays it formatted to the UI. I can only provide it with a format string. (If manipulating the number or resulting string is the only way to get it in the format we can probably do it, it would just take a good deal of refactoring, so I wanted to see if there's a simpler solution first. Hence the constraints.)
Just as an example of the output I'm looking for, consider the following code:
var myFormat = "{0:######.00}";
Console.WriteLine(string.Format(myFormat, 1234.1234));
Console.WriteLine(string.Format(myFormat, 5));
The code above currently outputs 1234.12 and 5.00, but I would like it to output 123412 and 500 just by changing myFormat. Is there a way to do this?
If only the format string is what you can change, there's probably no way to remove the dot.
However, you can implement your own Formatter, as MSDN's example.
string.Format(new CustomerFormatter(), "{0}", 1234.1234)

C# 6.0, .NET 4.51 and VS2015 - Why does string interpolation work?

After reading the following:
CLR Needed for C# 6.0
Does C# 6.0 work for .NET 4.0
it seemed to me that aside from String Interpolation any project I compiled in VS2015 against .NET 4.51 could use the new C# language features.
However I tried the following code on my dev machine using VS2015 targeting 4.51:
string varOne = "aaa";
string varTwo = $"{varOne}";
if (varTwo == "aaa")
{
}
and not only did I not receive a compiler error, it worked as varTwo contained aaa as expected.
Can someone explain why this is the case as I would not have expected this to work? I am guessing I am missing what FormattableString really means. Can someone give me an example?
As mentioned in the comments, string interpolation works in this case as all the new compiler does is convert the expression into an "equivalent string.Format call" at compile time.
From https://msdn.microsoft.com/en-us/magazine/dn879355.aspx
String interpolation is transformed at compile time to invoke an equivalent string.Format call. This leaves in place support for localization as before (though still with traditional format strings) and doesn’t introduce any post compile injection of code via strings.
The FormattableString is a new class allows you to inspect the string interpolation before rendering so you can check the values and protect against injection attacks.
// this does not require .NET 4.6
DateTime now = DateTime.Now;
string s = $"Hour is {now.Hour}";
Console.WriteLine(s);
//Output: Hour is 13
// this requires >= .NET 4.6
FormattableString fs = $"Hour is {now.Hour}";
Console.WriteLine(fs.Format);
Console.WriteLine(fs.GetArgument(0));
//Output: Hour is {0}
//13
Can someone explain why this is the case as I would not have expected this to work?
This works since you're compiling with the new Roslyn compiler which ships with VS2015, and knows how to parse the string interpolation syntactic sugar (it simply calls the proper overload of string.Format). If you'd try to take advantage of .NET Framework 4.6 classes that work nicely with string interpolation, such as FormattableString or IFormattable, you'd run into a compile time error (unless you add them yourself. See bottom part of the post).
I am guessing I am missing what FormattableString really means.
FormattableString is a new type introduced in .NET 4.6, which allows you to use the new string interpolation feature with a custom IFormatProvider of your choice. Since this can't be done directly on the interpolated string, you can take advantage of FormattableString.ToString(IFormatProvider) which can be passed any custom format.

C# Parse text file

I am trying to parse a file in MVC C#, see the format below. Since its not in JSON I cannot use the Javascript serializer to deserialize to an object. The other option is use to LINQ and read line by line and retrieve the desired values. Could any one recommend a more efficient way to do it.
The first field I need to retrieve is the ASSAY NUMBER (for example value 877) from ASSAYS
and then the ASSAY_STATUS field from TEST_REPLICATE which could be multiple nodes. Thanks
LOAD_HEADER
{
EXPERIMENT_FILE_NAME "xyz.json"
EXPERIMENT_START_DATE_TIME 05.21.2012 03:44:01
OPERATOR_ID "Q_SI"
}
ASSAYS
{
ASSAY_NUMBER 877
ASSAY_VERSION 4
ASSAY_CALIBRATION_VERSION 1
}
TEST_REPLICATE
{
REPLICATE_ID 1985
ASSAY_NUMBER 877
ASSAY_VERSION 4
ASSAY_STATUS Research
}
TEST_REPLICATE
{
REPLICATE_ID 1985
ASSAY_NUMBER 877
ASSAY_VERSION 4
ASSAY_STATUS Research
}
You could either hack something together or use a parser generator like ANTLR or Coco/R. Both can generate parsers in C#.
I'm more fond of using a parser-combinator (a tool for constructing parsers using parser building blocks) than parser generators. I've had passable experience with Piglet, which is written with/for C#, and is pretty easy to use, and amazing experience with FParsec, but it's written for F#.
As far as parser generators go, there are those suggested by stmax, and there is also TinyPG, which a member recommended me once.
You can also roll your own parser. I suggest basing it on some sort of state machine model, though in this simple case, like Kirk Woll suggested, you could probably get by with some plain old string manipulation.
I think the answer to this hinges upon whether or not there will ever be more than one ASSAY_NUMBER value in the file. If so, the easiest and surest way I know is to read the file line-by-line and get the data you desire.
If, however, you know that each file is unique to a specific ASSY_NUMBER, you have a much simpler answer: read the file as one string and use REGEX to pull out the information you desire. I am not an expert on REGEX, but there are enough examples online that you should be able to create one that works.

How to detect a C++ identifier string?

E.g:
isValidCppIdentifier("_foo") // returns true
isValidCppIdentifier("9bar") // returns false
isValidCppIdentifier("var'") // returns false
I wrote some quick code but it fails:
my regex is "[a-zA-Z_$][a-zA-Z0-9_$]*"
and I simply do regex.IsMatch(inputString).
Thanks..
It should work with some added anchoring:
"^[a-zA-Z_][a-zA-Z0-9_]*$"
If you really need to support ludicrous identifiers using Unicode, feel free to read one of the various versions of the standard and add all the ranges into your regexp (for example, pages 713 and 714 of http://www-d0.fnal.gov/~dladams/cxx_standard.pdf)
Matti's answer will work to sanitize identifiers before inserting into C++ code, but won't handle C++ code as input very well. It will be annoying to separate things like L"wchar_t string", where L is not an identifier. And there's Unicode.
Clang, Apple's compiler which is built on a philosophy of modularity, provides a set of tokenizer functions. It looks like you would want clang_createTranslationUnitFromSourceFile and clang_tokenize.
I didn't check to see if it handles \Uxxxx or anything. Can't make any kind of gurarantees. Last time I used LLVM was five years ago and it wasn't the greatest experience… but not the worst either.
On the other hand, GCC certainly has it, although you have to figure out how to use cpp_lex_direct.

Magic strings for converting DateTime to string Using C#

I was greeted with a nasty bug today. The task is pretty trivial, all I needed to do is to convert the DateTime object to string in "yyyymmdd" format. The "yyyymmdd" part was stated in the development doc from the external software vendor. So, I conveniently copied the string from their file and pasted to my code. So I got the next
public string GetDateString(DateTime dateTime)
{
return dateTime.ToString("yyyymmdd");
}
Pretty simple. So simple that I didn't feel like to unit test the method. 20 minutes later, when other parts of my component are done. I started the app to check if things went right. Almost immediately I notice some supposed-to-be date field in my web page is displaying 20091511! This can't be right, there is no 15th month of a year. So, I rushed back to my code to check possible errors. It turns out the that I should have used "yyyyMMdd" instead of "yyyymmdd" when converting DateTime to string.
Admitted, this bug was due to my lack of attention to details. The difference between "mm" and "MM" are cleared stated in all C# references. I still would like to argue that it's pretty easy to overlook the differences if one doesn't work with this kind of tasks everyday.
My question is: Is there a clean(i.e. no magic string) way to do the coverings in one line of code? Thereturn dateTime.Year + "" + dateTime.Month + "" + dateTime.Day; code seems to be working but it's too much like hacking.
Update: Looks like the string format way is the best C# can offer. Maybe I am being brain washed, but I still think this kind of programming style belongs to low-level languages such as c.
String.Format("{0:0000}{1:00}{2:00}", dateTime.Year, dateTime.Month, dateTime.Day);
You could use this instead, I prefer the terse format though. Instead of 00 you can also use MM for specific month formatting (like in DateTime.ToString()).
See here: .NET Custom Date and Time Format Strings
return dateTime.Year.ToString() + dateTime.Month + dateTime.Day;
You don't need to keep adding empty strings, string+number returns string already and addition is interpreted from left to right.
Do note that that line doesn't return what you think it does, what you really want is:
return dateTime.Year.ToString("0000") + dateTime.Month.ToString("00")
+ dateTime.Day.ToString("00");
If that format string bugs you that much, at least make sure it is in one place. Encapsulate it e.g. in an extension method:
public string ToMyAppsPrefferedFormat(this DateTime date) {
return date.ToString("ddMMyyyy");
}
Then you can say date.ToMyAppsPrefferedFormat()

Categories