Get date from DatePicker using c# in windows store app - c#

I want to insert date value in my database I have a class which have a date time attribute like this
public DateTime BookingDate { get; set; }
I have a date picker in my xaml page named datepicker . I want to insert only date value , How to get date using c#??

You can use the Date Property , follow the documentation
DateTimeOffset sourceTime = YourDatePicker.Date;
BookingDate = sourceTime.DateTime;
To convert back to offset and bind to datetimepicker
DateTime newBookingDate;
newBookingDate = DateTime.SpecifyKind(BookingDate, DateTimeKind.Utc);
DateTimeOffset bindTime = newBookingDate;
YourDatePicker.Date = bindTime;
Adding a DatePicker (XAML)

Using an MVVM Pattern:
View (XAML):
<DatePicker Date="{Binding DateOffset, Mode=TwoWay}" />
ViewModel (C#):
private DateTime Date { get; set; }
public DateTimeOffset DateOffset
{
get { return DateTime.SpecifyKind(Date, DateTimeKind.Utc); }
set { Date = value.DateTime; }
}

Related

Best way to Pass Typescript Date property as a parameter to a Web Api 2.0 method

I have a date picker in html which is bound to a Date property of an employee.
ex: i have selected the date as "Thu Feb 22 2018 00:00:00 GMT+0530 (India Standard Time)".this is the value i get when i log in console.
But when i tried to debug in C# the value is changed.
{21-02-2018 18:30:00}
How to handle or work with the typescript date object when passing it to a API method and displaying it back
My typescript Model
export class Visitor {
public id: number;
public firstname: string;
public lastname: string;
public dob: Date;
public genderId: number;
public age: number;
}
and C# model
public class Visitor
{
public int Id { get; set; }
public string Lastname { get; set; }
public string Firstname { get; set; }
public int Age { get; set; }
public DateTime DOB { get; set; }
}
As long as you are passing a valid Date object you should be fine.
Your problem probably lies in your Culture settings in .NET side.
Can you please try doing this in your controller action:
var culture = new CultureInfo("gu-IN");
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
Since you provide no code, this is merely a guess.
When you are printing in console, browser is printing the date in local timezone which is India in your case. When you are retrieving the value on server, C# is treating date in UTC. That is why you see a difference of 5.30 hours. India time is UTC + 5.30 Hours.
If you are storing the date value in UTC format on server side then convert the value of date object from client side to UTC using the libraries such as momentjs.
While retrieving the value from server, send the UTC value from server and convert it to local time zone using libraries such as momentjs. I think this strategy will work.

WebAPI - Bind Datetime dd/MM/yyyy hh:mm:ss

I have a intranet application using WebAPi and I'm having trouble binding the DateTime value to my model. I need the following format dd/MM/yyyy hh:mm:sss
XHR Post Data
Start=14/12/2015 02:44:09
End=14/12/2015 02:44:10
X-Requested-With=XMLHttpRequest
Config
<globalization uiCulture="en" culture="en-GB" />
Model Properties
[JsonConverter(typeof(CustomDateTimeConverter))]
public DateTime Start { get; set; }
[JsonConverter(typeof(CustomDateTimeConverter))]
public DateTime End { get; set; }
As you can see I've tried using a custom JSON converter on the properties.
public class CustomDateTimeConverter : IsoDateTimeConverter
{
public CustomDateTimeConverter()
{
base.DateTimeFormat = "dd/MM/yyyy hh:mm:ss";
}
}
The issue seems to be with the day or month being the other way round i.e MM/dd/yyyyhh:mm:ss.
Any ideas how I can get this binding in properly? Do I need a custom binder or JSON serializer?

store only date in database not time portion C#

I have a test class and an ExecutionDate property which stores only date but when we use [DataType(DataType.Date)] that also stores the time portion in database but I want only date portion.
public class Test
{
[Key]
public int Id { get; set; }
[DataType(DataType.Date)]
public DateTime ExecutionDate { get; set; }
}
Is any way to store only date on time portion in db using Entity Framework? Please help me....
I have added snapshot when use [DataType(DataType.Date)] that stores time portion 00:00 I want remove that
I think you are trying to specify database column type. You could use data annotations as described in this article.
Here is an example :
[Table("People")]
public class Person
{
public int Id { get; set; }
[Column(TypeName = "varchar")]
public string Name { get; set; }
[Column(TypeName="date")]
public DateTime DOB { get; set; }
}
By default, string is translated to nvarchar, we have changed that here. Also Datetime (this is what you asked I suppose) which by default maps to datatime in sql server, is changed to date which stores only the date portion and not the time portion of a DateTime value.
On EF core one may add override OnModelCreating in DbContext class.
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Test>().
Property(p => p.ExecutionDate)
.HasColumnType("date");
}
As David said above, once you bring that data into the application it will be a DateTime with the timestamp added onto the date. This would be the same result too if you stored the date as a string and used Convert to change to a DateTime for any manipulation:
string date = "2015-11-17";
var dateTime = Convert.ToDateTime(date);
Unless you want to manipulate strings in your application to avoid the timestamp, you can only work with DateTime. For display purposes though, you can always format the date and remove the timestamp:
var dateTime = DateTime.Now;
var formatDate = dateTime.ToString("yyyy-MM-dd");
In .NET 6 now you have new special type - DateOnly
More info here:
https://github.com/dotnet/efcore/issues/24507
https://www.stevejgordon.co.uk/using-dateonly-and-timeonly-in-dotnet-6
Change datatype on the database from Datetime to Date type
Is it really an issue for you anyway? You may want time in there at some point,
Change DateTime to nvarchar(10) in database
if u use DateTime in database 00.00.00 will be automatically assigned by database
string date = DateTime.Today.ToShortDateString();

how to format a date inside a collection of objects using linq in c#

I have a list of objects in my collection and need to format the date on an object date property (NoteDate) to show dates in the format like "dd'/'MM'/'yyyy HH:mm:ss" whereas in database the format of the date is like '2015-02-19 00:00:00.000'. Below is my object
public class Note
{
public int Id { get; set; }
public string NoteText { get; set; }
public DateTime? NoteDate { get; set; }
}
and I populate the collection as below
var notesList= _uow.Find<Note>(n => n.FK == leadId).ToList();
how can we write the query to get the desired date format?
thanks
You are, properly, storing the date in a DateTime? object. DateTime is simply a storage mechanism.
What you are really interested in is how to display the DateTime in some UI.
So here's the steps your Date/Time is going to take:
Get returned as query content from the database
Get stored in the DateTime property
Be shown to the user
To format a value from a DateTime object there are several options - check out the methods on the DateTime class.
Your dates will be represented as a DateTime instance .. how .NET decides to represent dates.
When you're displaying them to your user/using them for display somewhere, you can simply format them at that point. For example:
var notesList = _uow.Find<Note>(n => n.FK == leadId).ToList();
var thirdNoteDateString = notesList[2].NoteDate.ToString("dd MM yyyy");
Or, perhaps in a Razor view (if this was an MVC application):
#foreach (var n in Model.Notes) {
<p>#n.NoteDate.ToString("dd MM yyyy")</p>
}
Hopefully that shows the difference. How the date is presented is up to you when you decide to present it.
you should not modify the content of your buisness object just for a Show purpose,
You should use a converter or a StringFormat like :
<TextBlock Text="{Binding Date, StringFormat={}{0:MM/dd/yyyy}}" />
see this question for more info

DisplayFormat with CultureInfo DateTime

I'm trying to get set the DisplayFormat of a public property to the current cultureinfo datetime format. The class will be used for Silverlight Datagrid.
[DisplayFormat(DataFormatString=CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern.ToString())]
public DateTime createDate { get; set; }
It says, only that the argument can only be constant and typeof parameter...
Any ideas?
UPDATE, I tried Lukazoid solution but the Silverlight datagrid ignores the data annotations. The datagrid colums are added in codebehind because of localization.
The column looks like this:
DataGridTextColumn tcCreateDate = new DataGridTextColumn();
tcCreateDate.Header = SilverlightApplication.Resources.ContentGrid.dgCreateDate;
tcCreateDate.Binding = new Binding("createDate");
Attribute values must be constant or a result of the typeof syntax.
If you want to use the short date format for the current culture, use the following format string:
[DisplayFormat(DataFormatString = "{0:d}")]
Update
I can see your updated code to add the DataGridTextColumn, try this to add the StringFormat:
DataGridTextColumn tcCreateDate = new DataGridTextColumn();
tcCreateDate.Header = SilverlightApplication.Resources.ContentGrid.dgCreateDate;
tcCreateDate.Binding = new Binding("createDate") { StringFormat = "{0:d}" };
By default, silverlight uses en-US as the current culture for all bindings (regardless of your system settings), this means the StringFormat will result in a US format of the date. See here for a solution to ensure your current settings are taken into account.
Tried like this
public class Foo
{
[DataType(DataType.DateTime)]
public DateTime createDate { get; set; }
}
This will display with the date base culture of your project

Categories