I get a DateTime in SQL Server DataBase and want to display it in Input:
<input class="form-control" type="date" name="ExpireDate" id="expiredate" runat="server" value="31/12/2016" style="height: 30px; width: 267px">
and here is my C# codes:
Medicine med = new Medicine();
int a = GridView1.SelectedIndex;
med.ID = int.Parse(GridView1.DataKeys[a].Value.ToString());
DataProcess bal = new DataProcess(); DataTable dt = bal.getInfo(med)
expiredate.Value = Convert.ToDateTime(dt.Rows[0][5]).ToString("dd/MM/yyyy");
I put a break point just after the last line , I saw dt.Rows[0][5] got "{2017/5/31 0:00:00}" and expiredate.Value got "31/05/2017",but it just shows nothing without error in webpage. And this DateTime record is inserted into DataBase through exactly the same Input, I just don't know how to display it in the same Input when I pull it out from DataBase.
First time to ask, many thanks!
The problem here is the format of html date input and asp.net DateTime doesn't match. Html date input displays mm/dd/yyyy but the format behind is yyyy-MM-dd.
Try using expiredate.Value = Convert.ToDateTime(dt.Rows[0][5]).ToString("yyyy-MM-dd");
Hope this helps.
It seems that you are pushing a date inside a input field which is date type. But this won't work. Because html do not support the default value for raw date format. So you have to customize the date field using a javascript. However if ou take any help from Razor Html helper then you would be able to do this either not as you are on .NET framwork. Easily you can take help from previous answers jQuerydatepicker, here you can set a default date through javascript, which will show on your input field.
Related
I am trying to print pdf report using itextsharp pdf and all the values are correct except the values from column "Date" and "Time".
The date and time is displayed in a format like "dd/MM/yyyy tt hh:mm:ss" for eg. Date is: 08/10/2021 AM 12:00:00 and Time is: 30/12/1899 AM 07:46:37.
I have done everything mentioned below:
Inserting the date value from the datetimepicker as datetimepicker.Value.ToString("dd/MM/yyyy") and time value to be DateTime.Now.ToString("hh:mm:ss tt")
My datatype for Date and Time column in MS Access database is Date/Time
My database is showing correct formatted value and datagridview has incorrect format of Time column and generated pdf report have incorrect date and time format. My only question is how can this be possible as database consist of correct data but after displaying it in datagridview the format changes and even after printing it. Below I have attached images that will help you get the scenario.
Datatype for the column from database↓
Values in database↓
Values in Datagridview↓
you can try to set the DefaultStyle property like this
dataGridView1.Columns["YourColumn"].DefaultCellStyle.Format = "HH:mm:ss";
Or set it in the designer, whatever you like most.
In your database your Time column seems to have only a time value, but it has not. It uses the lowest possible date value, which is 30/12/1899 for an Access Database.
This happens when you only feed that column with a time, and no date. Acces (and other databases also) will simply use their lowest possible date value to fill up the missing date value.
The DataGridView therefor has no choice but to also show the date along with its time.
The property above will simply instruct the DataGridView to not show the date part, only the time part.
If you need to display the time in code in C#, you could use this
YourDateTimeVariable.ToString("T");
But, since you are storing both date and time in datetime columns, why do you store them seperate ?
You could just store them in one column, and show/use only the part you need.
EDIT
to respond to the code you posted in the comments (please add this code in your question, not in the comments)
change this
invoicesDatagridview.Rows[i].Cells[1].Value.ToString())
into this
((datetime)invoicesDatagridview.Rows[i].Cells[1].Value).ToString("T"))
in case this column can by null you will need some extra checks to avoid cast errors.
Also, the format in the GridCell willl never be used in a ToString(), you are doing the ToString() on the value, not on the display text.
Try the code above to fix this
EDIT
To respond to your comment below:
Printing code is not the point. I just want to know that how can datagridview cell value and print value be of different format –
karan ugale
By setting the DefaultCellStyle you tell the DataGridView what format to use to display the value. When you print this value with your own code using ToString(), how on earth should this ToString() know of the DefaultCellStyle setting ? The print code with ToString() has absolutly no connection with the DataGridView, you just pass it the value nothing more.
Look at this example
invoicesDatagridview.Rows[i].Cells[1].Value.ToString())
this can be written like this
var someValue = invoicesDatagridview.Rows[i].Cells[1].Value;
someValue.ToString();
now tell me, how should someValue.ToString() know of any format ?
The epoc of data type Date in Access is 1899-12-30, and as you display both date and time, that date is displayed as well.
In .Net you can apply the format string "T" to display hour-minute-second only. For example:
DateTime time = new DateTime(1899, 12, 30, 8, 12, 16);
Console.WriteLine(time.ToString("T"));
// 08:12:16
In my ASP.Net app, I have a textbox set to be a datepicker:
<asp:TextBox ID="uxDateTimeLocalTextbox" runat="server" TextMode="DateTimeLocal"></asp:TextBox>
When the user enters the datetime, initially its a string and must be converted to DateTime format before I send it back to my SQL Server table (where that column is in datetime format):
DateTime dateTimeOriginalEmail = Convert.ToDateTime(uxDateTimeLocalTextbox.Text);
Now, I have created functionality that will do the reverse, and populate the textbox with a value stored in the SQL table. I would think that I need to take that value and convert it back to a string. So, I tried the below (no errors were thrown) but I don't see the textbox being populated with the value from my table. I am using this method on other textboxes and dropdowns and they work fine. Any suggestions on how to get this to work? (Note: MM/DD/YYYY HH:MM AM/PM)
uxDateTimeLocalTextbox.Text = ticketInfo.Rows[0]["DateTimeOriginalEmail"].ToString();
uxDateTimeLocalTextbox.Text = newDate.ToString("yyyy-MM-ddTHH:mm");
this worked for me: (VB code but easy to change to C#)
If IsDate(dr("cnnReminder")) = True Then txtNoteReminderTS.Text = Format(dr("cnnReminder"), "yyyy-MM-ddTHH:mm")
ps. dr is a DataRow and cnnReminder a SQL DateTime
https://stackoverflow.com/a/31854660/2939161 LEM2802 solved it!
txtDate.Text = DateTime.Now.ToLocalTime().ToString("yyyy-MM-ddTHH:mm");
I want to create a simple ASP.Net form, that will get birth dates.
I have a model with this property:
[DataType(DataType.Date)]
public DateTime? BirthDate{ get; set; }
and in my view (is using the datepicker):
#Html.LabelFor(model => model.BirthDate)
#Html.TextBoxFor(model => model.BirthDate, new { #class = "form-control date-picker" })
#Html.ValidationMessageFor(model => model.BirthDate, "", new { #class = "text-danger" })
The only one setting on my javascript datepicker is:
format: 'L'
because I want show dates without times.
Now, I can't save, because of the validation error:
The value '12/23/2000' is not valid for BirthDate.
Now, I KNOW, its a globalization error... I need set culture in <globalization> element in web.config, etc...
But, have you noticed I set no formats (except the datepicker format "L")? I want that form get birthdates from people in any country, no a specific culture/format etc.
Is this possible? How can I do it?
Edit:
which date picker are u using?
The JQuery one, but this is not a requeriment, I can change to any datepicker that can easily handle different save formats "yyyy-mm-dd" and display format.
Which locale your server is located and which format do you prefer to work within your MVC code and to persist in database?
I dont know where my customer will host the site, its AWS... I prefer work with en-us.
Assuming that your datepicker can return the selected date in Date() js object. I would suggest to convert the date value in to a standard format like ISO8601. So what you have to do is to attach a onChange event on your date picker and convert the selected Date() value into ISO8601 format. You may assign this converted value to a hidden field (simply date.toISOString()).
MVC .net parser also understand ISO8601 format so when your form data is posted on server it is parsed to correct date value. See this question also.
I have create a jsfiddle using jquery UI datepicker. It uses a altFormat and altField which can be used for internal date format irrespective of whatever date format is shown to user in actual date input field.
Find the jsfiddle here - https://jsfiddle.net/Prasoon1983/kyjvwkLd/2/
$("#dob").datepicker({
altFormat: "yy-mm-dd",
altfield:"#dobInternal"
});
$( "#dob" ).datepicker( "option", "altField", "#dobInternal" );
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<input type="text" id="dob" />
<input type="text" id="dobInternal" />
I have used an input control for display purpose but you can use a hidden input.
Hope it helps.
Make your property as below
[RegularExpression(#"(\d{2}|\d{1})[/](\d{2}|\d{1})[/]\d{4}",ErrorMessage ="Birthday field must be ad dd/mm/yyyy format.")]
public DateTime? BirthDate{ get; set; }
Above regex only for dd/mm/yyyy format.If you need alternatives you must add that sign in [/].
Type of birthdate property of ViewModel can be string now.You can convert it to DateTime when you need
Globalization is really hard. But if you relaying on Javascrip then you can display selected date in one format and send it to server using different one e.g. ISO standard.
On server side I would prepare strict validator - e.g. accept only date in ISO format. When you receive request with some strange input then respond with error (with proper message).
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.
So I'm populating a DATE field in MySQL table from the DateTimePicker and on the other form I need to show the date in the textbox in "dd.MM.yyyy" format, but for some reason it populates the textbox in "MM/dd/yyyy HH:MM:SS" format.
I'm populating it simply like this:
tbDate.Text = dt.Rows[0][14].ToString();
How do i change the format?
Try following code
tbDate.Text = ((DateTime)dt.Rows[0][14]).ToString("dd.M.yyyy");
I need to show the date in the textbox in "dd.MM.yyyy" format
you need to first cast the value into DateTime type and then pass your Custom Date Format String to the ToString() function
Try This:
tbDate.Text = ((DateTime) dt.Rows[0][14]).ToString("dd.MM.yyyy");
Instead of changing the format in your C# code, directly fetch the date in the required format from database.
You can use the following query to fetch the date in dd.MM.yyyy format
select DATE_FORMAT(date_column,'%d.%m.%Y') FROM table_name;
Please refer this SQLFiddle Example
And then you can use your following code as it is,
tbDate.Text = dt.Rows[0][14].ToString();
Hope this helps :)