Change input date format for all devices - date

how I can change to "DD/MM/YYYY" date format for all devices.
public class ClassA
{
[Column(TypeName = "date")]
public DateTime? Bdate { get; set; }
}
<input type="date" asp-for="#Model.Bdate">
output : 24-Nov-2021
this is right in my computer , but not right in other computers and output : "11/24/2021".

First of all, the format you run out is MM/dd/yyyy, and I run it locally in 11/24/2021 style. You check your windows time setting to see if the dd/MM/yyy format is set, and you want to use it This format can be formatted like this:

Related

How Do I Format Date in Model or Linq Query for Controller Output

I have an API controller that renders a JSON result which is used by the infinite scroll plugin. Unfortunately, I don't see any way to format the output using the plugin itself, so I have to make sure the output is properly formatted before it is sent to the controller.
I have run into a problem with DateTime because all the examples I can find for formatting it rely on using server side code in the view. That is not an option with infinite scroll.
Preferably this should be done in the LINQ query or the model. I tried changing my model to:
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime? Date
{
get;
set;
}
That did not work. Likewise, changing the part of the select clause of the link query that says Date = p.Date to stuff like Convert.ToDateTime(p.Date).ToString("dddd MMMM dd, yyyy") doesn't work because you can't implicitly convert a string to date or something. That last example is exactly how I do it in the view.
How do I replicate that output in the JSON of an API controller?
NEW: The same seems true with decimals. I have prices that should include two decimals, but the JSON output in the controller only has as many as the user put in. This results in stuff like $20.5 followed by $0 and $22.55. The last of course being correct.
My price model looks like this:
[Required(ErrorMessage = "Price Required!")]
[Range(.00, Double.PositiveInfinity, ErrorMessage = "Must Be Positive Number!")]
[Display(Name = "Price:")]
[DataType(DataType.Currency)]
[Column(TypeName = "decimal(18, 2)")]
public decimal? Price { get; set; }
Try this...
public DateTime? Date { get; set; }
public string StringDate
{
set => Date?.ToString("0:MM/dd/yyyy")
}

Saving DateTime to sql without milliseconds

How do I save datetime property in EF without the milliseconds?
I I save it like this:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "
{0:MM/dd/yyyy}")]
[Column(TypeName = "datetime2")]
public DateTime ProcessingDateTime { get; set; }
I get data with milliseconds?
Any Ideas?
tX
Tally
For those that have encounter this problem, there is a away to solve this problem in a agnostic way agnostic in EF CORE:
1-go to the OnModelCreating
2- add to the property the extension method HasConversion, that will remove the milliseconds from the datetime, in both reads and writes
builder.Entity<Table>().Property(u => u.Date).HasConversion(dt => dt, dt => dt.AddTicks(-dt.Ticks % TimeSpan.TicksPerSecond));

How to bind multiple form elements to a single variable with the Play! framework

I am using the Play! framework, version 1. I have a form with 3 different select elements for day, month and year. I want to bind these to the birth date of a user (public Date birthDate defined in class User). How can I do this? Thanks.
You can create three setters getters in your class for day, month and year and update your date with these values. The best way to do that is to use joda date classes
public class MyClass {
public DateMidnight birthDate;
public int getBirthDateYear() {
return birthDate.getYear();
}
public void setBirthDateYear(int year) {
birthDate = birthDate.withYear(year);
}
}
and same thing with "monthOfYear" and "dayOfMonth"
I don't think it's worth fussing about with anything in the model, play can do this all in the controller, it's a bit of logic but should be no big deal in a smaller app. Assuming your select boxes POST numbers in your controller and you send other user stuff that mapped properly by name to user properties:
public static void save(User user, String day, String month, String year) {
DateFormat formatter = new SimpleDateFormat("MMddyy");
Date birthDate = formatter.parse(month + day + year);
user.birthDate = birthDate;
user.save();
}

ASP.Net MVC 2 Model Validation Regex Validator fails

I have following property in my Model Metadata class:
[Required(ErrorMessage = "Spent On is required")]
[RegularExpression(#"[0-1][0-9]/[0-3][0-9]/20[12][0-9]",
ErrorMessage = "Please enter date in mm/dd/yyyy format")]
[DataType(DataType.Date)]
[DisplayName("Spent On")]
public DateTime SpentOn { get; set; }
But whenever I call ModelState.IsValid it always returns false because regex is not validating. I have matched the entered date (08/29/2010) against new regex using same pattern and it matches perfectly.
What am I doing wrong?
Actualy there is another workaround for this. You can simply subclass the RegularExpressionAttribute
public class DateFormatValidatorAttribute : RegularExpressionAttribute {
public DateFormatValidatorAttribute()
: base(#"[0-1][0-9]/[0-3][0-9]/20[12][0-9]")
{
ErrorMessage = "Please enter date in mm/dd/yyyy format";
}
public override bool IsValid(object value) {
return true;
}
}
in your Global.asax.cs on application start register the RegularExpression addapter for client side validation like so:
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(DateFormatValidatorAttribute),
typeof(RegularExpressionAttributeAdapter));
Now you get to have the build-in MVC regular exression validator client side and keep the DateTime as your property type
That's because regex applies to strings and not DateTime properties. If the user enters an invalid string which cannot be parsed to a DateTime instance from the model binder it will add a generic error message before your regex pattern executes.
You have a couple of possibilities:
Customize the error message in a resource file
Write a custom model binder
Use a string property (I feel guilty for proposing this :-))

Force the culture of a console command

I want to execute a msbuild script using a specific culture (en-US) as one of the tasks is trying to call a web service using aDateTime.ToShortDateString() as a parameter, and my current culture is uncompatible with the server's (english) format.
How to do it without altering my regional settings ?
I ended up by creating a specific task for changing the current culture like this:
public class ChangeCulture : Task
{
[Required]
public string Culture { get; set; }
public override bool Execute()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(Culture);
return true;
}
}
If you want to change the culture of your entire application then you can set the culture when the application starts like this:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", false);
You can read about setting it on MSDN.
Given your example though, that may be overkill. If you are trying to change just the ToShortDateString() to en-US there may be a more simple way. You can use the ToString() method instead and pass in a specific format, for example you can do:
aDateTime.ToString("MM/dd/yyyy");
More specifically you can use the pre-defined culture info with System.Globalization like this:
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");
string datePattern = culture.DateTimeFormat.ShortDatePattern;
string shortDate = aDateTime.ToString(datePattern);