Date is not taking proper format as Expected (dd/MM/yyyy) - c#

I want to insert date into database in dd/MM/yyyy format. For that I have written like below:
drExpInfo[0]["CHEQUE_DT"] = string.IsNullOrWhiteSpace(e.Record["CHEQUE_DT"].ToString())
? DBNull.Value : (object)Convert.ToDateTime(e.Record["CHEQUE_DT"]);
And it is working perfectly fine on my local machine, but on my server it is taking format as dd/MM/yyyy hh:mm:ss. So how to set the same format there too. Kindly suggest.

Use DateTime.ToShortDateString:
drExpInfo[0]["CHEQUE_DT"] = string.IsNullOrWhiteSpace(e.Record["CHEQUE_DT"].ToString())
? DBNull.Value : (object)Convert.ToDateTime(e.Record["CHEQUE_DT"]).ToShortDateString();
But, I suggest you keep the time part of your date (without using the ToShortDateString as it will insert a time set to midnight, cf. highlighted text in Oracle documentation below) when inserting and get the format you want (without time) when you're using the date.
From Oracle documentation:
Oracle Database automatically converts character values that are in the default date format into date values when they are used in date expressions.
If you specify a date value without a time component, then the default time is midnight. If you specify a date value without a date, then the default date is the first day of the current month.
Oracle Database DATE columns always contain fields for both date and time. If your queries use a date format without a time portion, then you must ensure that the time fields in the DATE column are set to midnight. You can use the TRUNC (date) SQL function to ensure that the time fields are set to midnight, or you can make the query a test of greater than or less than (<, <=, >=, or >) instead of equality or inequality (= or !=). Otherwise, Oracle Database may not return the query results you expect.
So you can convert you're date in any format you want in c#, removing the time part, Oracle will automatically set the time part of your date as midnight (00:00:00).

You can set CultureInfo;
var cultureInfo = new CultureInfo("en-GB", false).DateTimeFormat;
string result = Convert.ToDateTime(e.Record["CHEQUE_DT"], cultureInfo).ToString();

Check this Discussion
Here you can find two or more ways to setting date format while insert records into database.
insert into sampleDate(Start_Date) values (to_date('25-Jun-2017','YYYYMMDD'))

Try:
public static DateTime? DateFromString(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return null;
}
else
{
return DateTime.ParseExact(dateString, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
}
}
DateTime? date=DateFromString(e.Record["CHEQUE_DT"]);
drExpInfo[0]["CHEQUE_DT"] = date==null? DBNull.Value : (object)date);

Related

How to get the date only on datetime on c# and putnit on database

I was working on an information system that gathers the students information for the teachers. One part of it is outting the value of the datetime picker on the db via command.parameters.addwithvalue. So I'm asking if there is any way to parse the datetime oicker so that there would be only date appearing on the db. Currently, date and time (set date and 12:00:00 am is showing.
In SQL2016, can use the data type date instead of datetime if you don't need the time. If the column's datatype is datetime, you will always have a time associated with it (if you just provide SQL a date for the value, it will set the time to midnight - 00:00:00).
Date and Time datatypes in SQL: https://learn.microsoft.com/en-us/sql/t-sql/functions/date-and-time-data-types-and-functions-transact-sql?view=sql-server-2016#DateandTimeDataTypes
If you don't wan't to (or if you can't) change the data type in the database, then on the C# side you can at least make sure that all the times are normalized to midnight from a datetimepicker by using ControlName.Value.Date where ControlName is the name of your datetimepicker control. (Having all times normalized to midnight can make SQL query writing easier when all you really need is the date but you're stuck with a datetime data type)
DateTime.Date property in .net:
https://learn.microsoft.com/en-us/dotnet/api/system.datetime.date?view=netframework-4.7.2
Send datetimepicker text to Stored Procedue like varchar parameter with time.
And parse it in SP like this
create SP
#Date varchar(50)
as
declare #DateX smalldatetime
select #DateX=Convert(smalldatetime,substring(#Date,7,4) +'-' + substring(#Date,4,2) +'-' + substring(#Date,1,2))
I Have a C# function for this issue also;
public String ArrangeDate (string S)
{
FirstPoint = S.IndexOf(".");
SecondPoint =S.IndexOf(".",FirstPoint+1);
S= S.Substring(SecondPoint+1,4) + "-" +S.Substring(FirstPoint+1,SecondPoint-FirstPoint-1)+ "-" + S.Substring(0,FirstPoint);
return S;
}

asp.NET and SQL Server datetime issues

I am having hard time to store date information into the datetime column of SQL Server.
I get the input from the user for three columns:
Creation Date
Preparation Date
Next Preparation Date
I use calendarextender and format the date as "yyyy/MM/dd". When all the fields have date, they are stored in the DB as for instance, 16-10-2016 (dd-MM-yyyy).
At this point I have two issues:
These columns are optional, when some of them are empty my code does not work (I assume because datetime cannot be null). To overcome this, I am using the following code snippet but still does not work.
DateTime? creationDate= null;
if (creationDateTextbox.Text != null && creationDateTextbox.Text != "")
{
creationDate= Convert.ToDateTime(creationDateTextbox.Text);
}
When I fetch the dates from DB, they are shown as 10/16/2016 (MM-dd-yyyy) which is different how I formatted it. I would like to show it in the format user enters them.
Dates do not have a format while stored in a database. It is actually usually just a very large long that counts the number of milliseconds from a set starting date.
If you want to store the format you need to stop storing it as dates and instead just treat the text as text in the database, however if you do this you won't get the advantage of sorting or filtering by a date range because it will just be seen as text.
Date time doesn't have any format You can format is as a string, suppose your DateTime type database field dt which contain date as 10/16/2016 (MM-dd-yyyy) then you can convert it
string s = dt.ToString("yyyy/MM/dd");
The answer to one of your questions is here: MSDN
You can use data annotations to format the dates that you get from your SQL DB. I'm assuming that you're using EF6; if not, you can change the field to a varchar in SSMS, and store the date as a String.
And the second, I'm unclear about, but if what you want is for your SQL DB column to be optional, you can use the Optional data annotation for that.

GETDATE() always returns 12:00:00 AM

In my ASP.NET (C#) project, I'm inserting some data into a database.
INSERT INTO USERS (username,join_date) VALUES('Ali',GETDATE());
Now when I'm fetching the date from the database, I'm using DateTime.
SqlDataReader r = Command.ExecuteReader();
r.Read();
myDate = r.getDateTime(0);
And when I'm inserting this in some DIV, I do this.
"<div>"+myDate.ToLongTimeString()+"</div>"
I get the correct date as in day/month/year, but the hour is always 12:00:00 AM.
How can I get the exact time?
make sure join_date is of type DATETIME and not DATE in the database
http://msdn.microsoft.com/en-us/library/ms186724.aspx
Using DATE as your column type means you are only storing the date not the time.
Therefore when you read the value back into a DateTime object the system has to initialise the time part - to midnight.
Convert the column to DATETIME and you'll get the time component stored as well.
For more information on the difference see the MSDN page on Date and Time Data Types and Functions

DateTimeFormat issue when pass the parameter to MS-Sql stored procedure

I have a stored procedure, which has a parameter like #CurrentDate datetime, when I pass the value DateTime.Now from the front end (C#) to this stored procedure it is working fine.
But when I change the Date Format as English(India) in my system/server, that time DateTime.Now will return a value like 25-10-2012 PM 05:23:27. I am passing this value to stored procedure and I'm getting an error message like the following,
Msg 242, Level 16, State 3, Line 10
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Note : I don't want to use GETDATE() from Sqlserver, I want to pass the parameter from c#.
How can I solve this?
The problem with the date format is because you are converting it to a string and then back to a DateTime value. Depending on the culture settings on the specific server this may or may not work. It may also misinterpret the data, e.g. transforming a date from 2013-10-12 to 2013-12-10.
DateTime datet = new DateTime(year,month,day);
startDateParam.Value = datet;
endDateParam.Value = datet;
"note that the server stored datetime with format '1900-01-01 00:00:00.000'"
You can use this conversion from C#. Hope this helps
DateTime.Now.ToString(DateTimeFormatInfo.InvariantInfo)
You will need to convert the value to a valid DateTime using Convert function.
For more information : http://www.sql-server-helper.com/tips/date-formats.aspx
Storing dates in local timezones can cause headache when you launch internationally.
If you save current date using GETUTCDATE() on SQL Server side, you can get the time in user specific timezone as follows:
public DateTime GetDateByTimeZoneId(DateTime dateTime, string timeZone)
{
if (dateTime == null)
{
return null;
}
dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
return TimeZoneInfo.ConvertTimeFromUtc(dateTime, TimeZoneInfo.FindSystemTimeZoneById(timeZone));
}
You can then pass user relevant timezone like "GMT Standard Time"

1/1/0001 12:00:00 AM not Updating SQL 2008 Date field

this is just weird and is giving me a headache. I looked over my code and I don't see any logical errors causing it.
Any other date set to my birthDate DateTime variable in my class works when I add it as the value in my conn.AddParam, but when I send back 1/1/0001 12:00:00 AM (which was sent by setting it to MinValue) to SQL 2008's Date field, it remains the default which I have set to null in the databse for that field:
conn.AddParam("#birthDate", birthDate);
birthDate is type DateTime. It's set to DateTime.MinValue; I don't see why it wouldn't take this.
I may not be understanding the question, but I believe January 1, 1753 is the earliest date supported by SQL Server.
Source
If you need to go back that far, use DateTime2. It allows you to go back as far as 1/1/0001 http://technet.microsoft.com/en-us/library/bb677335.aspx
Just a guess but it might be caused by a casting issue. Since your birthDate variable has a time component (12:00 AM), SQL might be casting it to a DateTime before its inserted into the Date field. Since 1/1/0001 is an invalid SQL DateTime it might be having problems. Try setting your #birthDate parameter to birthDate.Date instead.
In SQL server 2008 :
Date data type : - will allow you to store only date (YYYY-MM-DD) and as range 0001-01-01 through 9999-12-31.Its accurate to 1 day
Time data type : It stores in the format hh:mm:ss:nnnnnnn , with range 00:00:00.0000000 through 23:59:59:9999999 and is accurate to 100 nanoseconds
DateTime2 : the format is YYYY-MM_DD hh:mm:ss:nnnnnnnm with a range 0001-01-01 00:00:00.0000000 through 999-12-31:59 9999999,accuracy is 100 nano seconds
DateTimeOffset:It includes additional information to track the time zone.The format is YYYY-MM-DD hh:mm:ss[.nnnnnnn][+/-]hh:mm with a range of 0001-01-01 00:00:00.000000 through 9999-12-31 23:59:50.9999999.storage 8 yo 10 bytes.
DateTime is a value type. Therefore if a DateTime variable hasn't been assigned it's value would be the default one which happens to be DateTime.MinValue. That's why when you explicitly set your birthDate to DateTime.MinValue it's treated as it was not assigned at all (e.g. as null) and thus gets replaced by the default value for that parameter in your stored proc.

Categories

Resources