C#: Dateformat in C# for Inserting to sql server - c#

I have a textbox with date format dd/MM/yyyy that I want to convert to the format yyyy-MM-dd to insert it into a database.
I tried
Convert.DateTime/DateTime.ParseExact
but it always give me the system's default date format.
I don't know any other method to convert it in C#...

You shouldn't be converting it to a string at all to insert it into your database. (I'm surprised at all the other answers which are recommending this approach.)
Instead, you should be using parameterized SQL, and set the value of the parameter to the DateTime value you've got. You should be using parameterized SQL anyway to avoid SQL injection attacks, and to keep your code and data separate. The fact that it avoids unnecessary string conversions (each of which is a potential pain point) is yet another benefit.
This part of your question suggests you've got a fundamental misconception:
I used Convert.DateTime/DateTime.ParseExact it always give me system date format.
Those methods will give you a DateTime. A DateTime doesn't have a format. When you call ToString you just get the default format for the current culture, but that's not part of the value. It's like with numbers - 16 and 0x10 are the same number, and the int doesn't "know" whether it's in decimal or hex; it's a meaningless concept.
All of this goes beyond your immediate problem, towards trying to keep your code base clean in terms of types. You should keep data in its most appropriate form for as much of the time as you possibly can, and make sure you understand exactly what that data means at all points. Conversions to other types (such as strings) for communication should be done only at API/system boundaries, and avoided even there if possible (e.g. using parameterized SQL as in this case).

There are many methods but none so useful and logical than using Parametrized SQL. Here's the Wikipedia page! For more information on Parametrized SQL statements, Visit this Coding Horror page!

There is actually no need to change it. This is just the display format, but the 'DateTime' object inside stays the same. Depending on how you want to insert, you can just use:
string dateValue = DateTime.Now.ToString("yyyy-MM-dd");
And insert this in your query string.
EDIT
But as Jon Skeet commented, building your query string manually like this should never be done. A cleaner approach like parameterized SQL or utilizing NHibernate should be your first concern.

Hope this works!
DateTime variable= Convert.ToDateTime(your date);

You can format it like this:
string sDateTime = Convert.ToDateTime(txtTextBox.Text).ToString("yyyy-MM-dd");
Edit
There are many ways to skin a cat when it comes to preparing information for entry into a database. My solution here answers the OP directly, however I very much acknowledge that there are better ways to do this.
I'd suggest reading through Jon Skeet's post on this page as well, as he raises some extremely valid points regarding the approach of the OP.
Hope that helps.

Related

C# .Net Linq and converting datetime to formatted sting

I have the query
var result = (from myView in db.loginSessions
where myView.machine.ToUpper().Equals(machine.ToUpper())
&& myView.start >= myStart
&& myView.end <= myEnd
orderby myView.start
select new loginSessionList {
Id = myView.id,
Machine = myView.machine.ToUpper(),
Start = myView.start.ToString("u"),
End = myView.end.ToString("u"),
User = myView.username
}).ToList();
I get ArgumentOutOfRange exceptions on the datetime conversions. I have tried different ToString conversion strings. I have tried the other To... date->string conversions offered by Intellisence. I have tried Convert.string(myView.start). Nothing has worked. I have googled and have found advice using all the things I have tried. Do I have to post-process the generated list?
What have I missed?
I have 3 rules for dealing with DateTimes that served me well:
Always store, retreive and transmit the UTC value. Translating into the proper local Timezone is the job of ToString(), wich asks Windows for the users timezone. You do not want to add timezones to your troubles.
Avoid store, retreive or transmission of DateTimes as strings. Keep it in proper types whenever possible
If you can not follow rule 2 (like when you deal with Serialsiation), at least pick a fixed Culture Format and String encoding on all endpoints. You do not want to get different Cultures or faulty implied Encodings to your existing troubles
So, the answer to my issue had nothing to do with Linq or .Net. #JoeEnos put me on the right track as mentioned in my comment to his comment. I had created a class to receive each row of query result. The date fields were initially DateTime types but I started having issues. I changed those fields to string and then ended up asking my question above.
Back when the receiving class still had the DateTime fields, all of the fields had lowercase names. I must have applied some sort of code formatting that CamelCased the field names. This meant that after serializing the results the CamelCased names could not be found and the javascript didn't care.
I fixed the field names in my js code, changed the field data types back to DateTime and all is good.
Thanks

How to use StepArgumentTransformation properly in Specflow(BDD)?

I encountered a scenario where i have to send an array of integers as parameter from specflow feature file. I could have used tables which i don't want to do as i have send as row[] or col[]. If i pass parameter as a string
eg: Given set the value as '470,471,472,472'
and receive it and do split in step definition file. How different is StepArgumentTransformation from the above scenario? Is any other benefit in using step argument transformation. I understand we can convert XML,Date or any object. Why do we have to use stepargumenttransformation???
I hope I understood the question correctly.
Specflow supports some automatic transformation out of the box, so things like converting to Date, Double, int etc etc, and it does these by default as there is no ambiguity about them. You can easily convert a string to a double or a Date as you know the locale being used.
Why isn't converting to arrays supported? I suppose it could be, but there is some ambiguity. What should the list separator be? a comma? What about locales that use that as a separator between the whole and fractional part of a number?
So providing a default implementation of something which converted a list to int[] or IEnumerable<int> could be possible, but its just likely to get some people asking why it doesn't work for them when they have used ☃ as a list separator.
It's better to leave the things with ambiguity to individuals to implement, rather than guess at the best implementation.
The StepArgumentTransformation you want is very simple to write and could be included in an external step assembly if you wanted to share it amongst many projects.
So to answer your many questions:
It's not really any different, it just encapsulates it in a single place, which is good practise, which is a benefit.
Yes you can convert any object.
You don't have to use StepArgumentTransformation, many people don't, but IMHO they make your life much easier

formatting dates incorrectly, trying to understand the reason

sorry if this question is a little ... strange, but I am a little lost to what is happening and how to control it. What I need to better understand is the following:
I have an ASP MVC application that works with Linq-To-SQL and an MSSQL server. The application is an inside (office only) website, and I am mentioning that so it wont sound that strange when I say that we wanted to ignore browser language, culture, date, whatever... settings and always display the date in the format "dd/MM/yyyy". Always.
So, now that I am testing a specific form in the website I encounter something very, very strange.
The first strange thing is that the date is not displayed on the screen correctly. Let me elaborate, I have a simple view that gets some data, read from the database, inside a model. So, as I fought for sometime with teaching the datetime object to display in a certain way on server level (meaning giving it an attribute like [Display(..)] or [DataType(...)] didn't force the date to look the way I want, so I simply wrote the following:
<input id="BirthDate" name="BirthDate" type="text" value="<%= Model.BirthDate.HasValue ? Model.BirthDate.Value.ToString("dd/MM/yyyy") : "" %>" class="text-box datepicker" />
However, even though I am specifically formatting the date to display "dd/MM/yyyy" in the input, it doesnt. When the browser settings are Dutch, the value inside this box is displayed with 'dd-MM-yyyy'.
I can somehow accept that, the browser is a smart guy(or gal) and identifies that the value in the box is a date and applies formatting according to the selected language settings. I don't know how to tell it not to screw with my dates, but I can get to believe that this is what happens. HOWEVER, what I am finding a lot difficult to accept is that THE Date formatting somehow goes back to the database. This sentance didnt really mean anything so I am explaining again. I have a table that has a few columns, one of them being a varchar(100). Super, and because of some very interesting designing, that field can contain text, dates and whatever.
So, because the field is a string, and later on I simply display it in a paragraph and dont need to do the whole dance of casting it to a DateTime object and then formatting it back when it gets in the view (which works so perfectly as I previously mentioned) I simply save it in the table in the correct format (dd/MM/yyyy).
Yea, but not really. My code would look like that:
var date = DateTime.Now;
db.EmployeeHistory log = new EmployeeHistory();
log.ActionType = 1;
log.EmployeeId = 1671;
log.At = date;
log.Context = "A TEST";
log.ObjectTitle = "Who cares";
log.EmployeeHistoryChangesSets.Add(new EmployeeHistoryChangesSet()
{ PropertyName = "TEST PROPERTY", NewValue = date.ToString("dd/MM/yyyy"), OldValue = date.ToString() });
dataContext.EmployeeHistories.InsertOnSubmit(log);
dataContext.SubmitChanges();
This is a of course a test, one that didnt make me happy at all. Because, if you are paying attention, there is a field in the database which is mapped to a string (varchar(...)) and then I am taking the Date, make it a string with the .ToString() method while formatting it into a "dd/MM/yyyy" format. So I am not using dates (well I am using a Date object to get the date, but I am converting it to a string) I am using only strings.
And somehow, for some reason that is truly escaping me, the string/date is saved in the database in the format: 'dd-MM-yyyy'. I really didnt expect it to behave in such a way. At first I was going to accept my fate, even though I was having a really hard time accepting that the database will take the liberty to format my input even though IT IS a string.
So, further testing showed me that the Date.ToString("dd/MM/yyyy") method actually returns the date in 'dd-MM-yyyy', depending on the browser language settings. Meaning that if I change my settings and it works correctly again ("dd/MM/yyyy").
So, my question is, what am I missing? Why is the .ToString() method not formatting the date correctly? Is my analisys correct or am I up and to the right on this one? If there is a good reason for that (even though I cant come up with one), should I just create my own extension method for DateTime class and implement the formatting mannualy or is there a better way?
I am really sorry for the long post (again). I would appreciate some clarity, as the whole project will behave this way. Thanks in advance

How can I create or set JodaTime DateTime objects with/to maximum value?

I am translating some C#-code to Java, and have chosen JodaTime's DateTime class, to replace C#'s System.DateTime.
In C# the DateTime class has a Field called MaxValue and one called MinValue, which returns the biggest and smallest possible value that the DateTime object can hold.
I am trying to achieve the same with the JodaTime api. I have read some suggestions on other posts
This one: Java equivalent of .NET DateTime.MinValue, DateTime.Today answers how to make today's date in JodaTime, but when answering the second half of the question, about Min Values, they turn to Calendar and Date
Likewise I have seen suggestions about passing a maximized long value as constructor parameter, but it was criticized for being dependant on classes that might be changed in the future, and therefor might not be compatible or accurat after API updates.
So, is there a single positively correct way to do this? If not, is there a good way to achieve this?
Java 8 LocalDate has two values. LocalDate.MAX and LocalDate.MIN
LocalDate.MAX - The maximum supported LocalDate, '+999999999-12-31'. This could be used by an application as a "far future" date.
LocalDate.MIN - The minimum supported LocalDate, '-999999999-01-01'. This could be used by an application as a "far past" date.
Note: these do not translate to Long.MIN_VALUE or Long.MAX_VALUE.
I suggest using Java 8 if migrating from C# and how date/time works is important to you, as it has closures AND a new DateTime API based on JodaTime. This new DateTime API is the one you should be using if you are worried about the future of an API.
I think you can assume that Long.MIN_VALUE and Long.MAX_VALUE will never change as they are based on the definition of how a signed 64-bit values work. (How 64-bit values work was standardised before you were born, most likely) You can also assume that Date will not change as it hasn't change much since it was released and since it has been replaced there is even less reason to change it. In theory it might be deprecated, but in reality there is still too much code which uses it.
IMHO, I use long to represent a time in milli-seconds ala System.currentTimeMillis() and I use Long.MIN_VALUE and Long.MAX_VALUE.
If you are concerned about using good API and future proofing your code, I suggest you avoid using Calendar. Not that it is all bad, but there are good reasons to want to replace it.

c#: tryparse vs convert

Today I read an article where it's written that we should always use TryParse(string, out MMM) for conversion rather than Convert.ToMMM().
I agree with article but after that I got stuck in one scenario.
When there will always be some valid value for the string and hence we can also use Convert.ToMMM() because we don't get any exception from Convert.ToMMM().
What I would like to know here is: Is there any performance impact when we use TryParse because when I know that the out parameter is always going to be valid then we can use Convert.ToMMM() rather TryParse(string, out MMM).
What do you think?
If you know the value can be converted, just use Parse(). If you 'know' that it can be converted, and it can't, then an exception being thrown is a good thing.
EDIT: Note, this is in comparison to using TryParse or Convert without error checking. If you use either of the other methods with proper error checking then the point is moot. I'm just worried about your assumption that you know the value can be converted. If you want to skip the error checking, use Parse and die immediately on failure rather than possibly continuing and corrupting data.
When the input to TryParse/Convert.ToXXX comes from user input, I'd always use TryParse. In case of database values, I'd check why you get strings from the database (maybe bad design?). If string values can be entered in the database columns, I'd also use TryParse as you can never be sure that nobody modifies data manually.
EDIT
Reading Matthew's reply: If you are unsure and would wrap the conversion in a try-catch-block anyway, you might consider using TryParse as it is said to be way faster than doing a try-catch in that case.
There is significant difference regarding the developing approach you use.
Convert: Converting one "primitive" data in to another type and corresponding format using multiple options
Case and point - converting an integer number in to its bit by bit representation. Or hexadecimal number (as string) in to integer, etc...
Error Messages : Conversion Specific Error Message - for problems in multiple cases and at multiple stages of the conversion process.
TryParse: Error-less transfer from one data format to another. Enabling T/F control of possible or not.
Error Messages: NONE
NB: Even after passing the data in to a variable - the data passed is the default of the type we try to parse in to.
Parse: in essence taking some data in one format and transfer it in to another. No representations and nothing fancy.
Error Messages: Format-oriented
P.S. Correct me if I missed something or did not explain it well enough.

Categories

Resources