override default DateTime format in C# [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am working in an application built in .NET framework 2.0 but I am running it in .NET framework 4.0, with SQL server as a database.
when I try to take date as a input from Calendar controller (Webforms) its in the format dd/MM/yyyy and this application using Convert.ToDateTime() to parse this date and it throws exception.
so how can I resolve this problem and is there any way that DateTime class object store the date in specific format means I want to store date in dd/MM/yyyy format even when I copy this date object to another, then both object should have same format.
and sorry for My English :p

Assuming you mean this Calendar control, you should just use the SelectedDate or SelectedDates property - let the control handle the conversions.
In general, you should avoid performing textual conversions unless you really need to. (This includes when you interact with the database - use parameterized SQL, and simply pass the DateTime values in the parameters.)

var result = DateTime.ParseExact("29/01/2014", "dd/MM/yyyy", CultureInfo.InvariantCulture);
You should avoid converting DateTime to string and back if you can help it.

Related

'string' to 'System.IFormatProvider' Error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am trying to get "ago" time within C# but am currently struggling as I get this Error.
Basically this is what I am trying.
var dateAgo = $"{DateTime.Now.Subtract(booking.CreatedAt.Date)}";
booking.createdAt.Date is where my date for my booking is saved.
I can show #dateAgo in my HTML but the problem is when I try something like
#DateTime.Now.Date.Subtract(booking.CreatedAt.Date).ToString("d")
which sadly does not work.
DateTime.Subtract() yields a TimeSpan object. ToString("d") is not a standard TimeSpan format string. See Standard TimeSpan Format Strings.
You want the custom format string "d" which outputs the number of days. For this, change "d" to "%d":
#DateTime.Now.Date.Subtract(booking.CreatedAt.Date).ToString("%d")
Or you can simply extract the Days from the returned TimeSpan object which will return the number of days:
#DateTime.Now.Date.Subtract(booking.CreatedAt.Date).Days.ToString()
Use DateTime.Now.Subtract(booking.CreatedAt.Date).Days
Subtract() produces a TimeSpan, which is incompatible with using the "d" format specifier by itself. Try something else, e.g. .ToString("%d") or .ToString("c").
Or if needed, the TimeSpan provides .Days, .Hours etc properties which can be used instead.

Date is not displaying in correct format [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am not that much experienced in asp.net MVC. I want to display date in correct format. But it is showing some number instead of that.
Below is my screenshot of the problem.
Here is my code where I convert date.
dateTime[i] = Convert.toDateTime(orderDetail.Rows[i]["joiningDate"].toString());
use this. you are not getting date in correct format so first convert it into string format and then to date time
Convert.ToDateTime(Convert.ToDateTime(orderDetail.Rows[i]["joiningDate"]).ToString("MM/dd/yyyy"))
To convert a date to a proper string, you can use DateTime.ToString(string format)
so:
DateTime.Now.ToString("dd-MM-yyyy")
will display as 10-03-2018.
So on your page you'll have to use .ToString on your date, with the format you want to use.

Why does DateTime.Parse() get wrong year when parsing dd-MMM date? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I created an application in which the user enter a month-year dd-MMM date as input, and this date is parsed using the DateTime.Parse() method. It is working fine on my PC.
Dim txtDate as String = combobox1.Text
Dim dtDate as DateTime = DateTime.Parse(txtDate)
Example:
DateTime.Parse("01-Dec")
Result:
2017-12-01 00:00:00
But when running this application on other machines, it returns 1899 year.
1899-12-01 00:00:00
After searching I found a similar question here: Time parsing Issue using DateTime.ParseExact() and it is marked as answered, but there is no solution for this situation
Does anyone knows what causes this problem?
Note: it is an old application I am working on. I know that it is recommended to replace it with a DateTime picker, but the issue is very confusing
Date.Parse without specifying an IFormatProvider will use the current user's Culture settings to determine what formats to parse, so 01/04/2017 will be 2017-April-01 on most computers (dd/MM/yyyy) but 2017-Jan-04 on computers in the US (MM/dd/yyyy).
If you're using the same format everywhere, you should use DateTime.ParseExact and provide an explicit format.
As for your specific problem, the string 01-Dec does not specify a year component, the computer must therefore infer the date, and how that date is inferred is often down to the Culture setting too.

Changing In DateTime Format [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have changed format to dd-mm-yy in backend of page, i want to save date in'dd-mm-yy' format e.g.'23-02-2015' in database.and retreieve it in this format, i am using datetime picker in the text field...i changed the format of date picker to my 'dd-mm-yyyy' but its not saving data in that format and cause the below error
String was not recognized as a valid DateTime.
Any suggestions?
Simply don't use strings to represent dates.
the DateTime struct of c# maps to sql server's datetime data type directly, meaning that you can simply send the DateTime struct as a parameter value in your SqlCommand object (I hope you are using parameterized queries or stored procedure. If not, then start using them right now, unless you want to be vulnerable to Sql injection attacks.)
Read here and there about the difference between Display format and storing format of date values in sql server.
"String was not recognized as a valid DateTime."
First , why aren't you sending datetime object ?
If you can't(!) , well ,
If your datetime object id dt so do dt.ToString("yyyy-MM-ddTHH':'mm':'sszzz", DateTimeFormatInfo.InvariantInfo)
This will be a valid iso datetime string.
The only truly safe formats for date/time literals in SQL Server, at least for DATETIME and SMALLDATETIME, are:
YYYYMMDD
YYYY-MM-DDThh:nn[:ss[:mmm]]

In ASP.NET MVC2, convert time user's timezone. How to get timezone info? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I stored datetime into database then i retrieve the values.. My server db is located other country. so when the value is retrieve it is taking other country date and time..
I tried in controller as follow,
if (item.CreatedDate == null)
{
item.CreatedDate = DateTime.Now;
var timeZone = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(item.CreatedDate, TimeZoneInfo.Local.Id, item.CreatedDate.Value).ToString();
}
I got line error here... How to correct it?
You're passing values that aren't even of the right data type. Read up on TimeZoneInfo so you know how to use it properly.
Also read:
Why you shouldn't use DateTime.Now
The timezone tag wiki
DST and Time Zone Best Practices
Also understand that somewhere here you actually have to know the user's time zone. Just calling TimeZoneInfo.Local.Id isn't going to work, because that is also the server's time zone. There's no magic performed by MVC to know the time zone of your user. You'll have to ask them for it, or employ some other strategy involving JavaScript.
From your comments, it appears you are looking for something like this:
// These should be stored in UTC. Do not store them in anyone's local time.
item.CreatedDate = DateTime.UtcNow;
item.UpdatedDate = DateTime.UtcNow;
// Then later when you want to convert to a specific time zone, do this
string timeZoneId = "India Standard Time"; // as an example
TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
DateTime localCreated = TimeZoneInfo.ConvertTimeFromUtc(item.CreatedDate, timeZone);
DateTime localUpdated = TimeZoneInfo.ConvertTimeFromUtc(item.UpdatedDate, timeZone);
Also, it seems like you might be using DateTime? (nullable datetimes) for your properties. It doesn't make sense to do that for these fields. They should be non-null in your database and always contain a value.

Categories