Converting Datetime C# type to Date javascript in asp.net mvc razor application
I'm still with FosterZ, but you should also get rid of the +
as well.
So instead of
start: new Date(@m.Begin_date.Year +"," + @m.Begin_date.Month +","+ @m.Begin_date.Day ) ,
try
start: new Date(@m.Begin_date.Year , @m.Begin_date.Month , @m.Begin_date.Day ) ,
If that still doesn't work, then view the source of the page, and see what is being put into the Javascript there. It's most likely not what you're expecting it to be. If you can't figure it out, add that to your question and we can take a look at it.
How to format dates in MVC 5 Razor
I am using the PagedList NuGet package which makes the Html helper calls a little different. I was able to format the date by specifying the date format in the data model constructor and then using the display helper.
In the data model:
[DisplayFormat(DataFormatString = "{0: MM/dd/yyyy}")]
public Nullable<System.DateTime> ExpireDate { get; set; }
In the razor:
<table class="table-condensed">
<thead>
<tr>
<th>Company</th>
<th>Contract No</th>
<th>Description</th>
<th>Expires</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@Html.ActionLink(@item.CompanyName, "ViewContract", new { contractID = @item.ID }) </td>
<td width="200">@item.ContractNumber</td>
<td>@item.Description</td>
<td>@Html.DisplayFor(modelItem => item.ExpireDate)<td>
</tr>
}
</tbody> </table>
How to convert string to DateTime object with current time in mvc
If you know the correct culture for the date string, you can use DateTime.Parse to parse the date and then add the current local time :
var finalDateTime = DateTime.Parse("23/12/2017",CultureInfo.GetCultureInfo("en-GB"))
.Add(DateTime.Now.TimeOfDay);
Many countries use the dd/MM/YYYY format, so you can use one as a fallback even if you don't know the actual locale.
If you don't know the locale, only the format, you can use ParseExact to parse the date only :
var finalDateTime = DateTime.ParseExact("23/12/2017","dd/MM/yyyy", CultureInfo.InvariantCulture)
.Add(DateTime.Now.TimeOfDay);
The returned value is a date whose value is December 23, 2017 and the current time.
Don't be confused by the debugger's display. Dates have no format, they are binary values. The debugger has to display the value in some way though. If, as many developers do, you use a US locale, you'll see the date as MM/dd/YYYY
. If you check the Month property though, it will be 12.
Convert C# DateTime to Javascript Date
Given the output you're stuck with, I can't think of any better way to catch a DateTime
of 0 on the javascript side.
Date.parse
should work for your parsing needs, but it returns number of milliseconds, so you need to wrap a Date constructor around it:
var date = new Date(Date.parse(myCSharpString));
For the return date, you simply want
date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + (date.getDate() + 1);
(date.getMonth
and date.getDate
are 0-indexed instead of 1-indexed.)
Fiddle: http://jsfiddle.net/GyC3t/
EDIT
Thanks to JoeB's catch, let me do a correction. The date.getMonth()
function is 0-indexed, but the date.getDate()
function is 1-indexed. The fiddle was "working" with the +1 because date.getMonth works in local time, which is before UTC. I didn't properly check the docs, and just added 1, and it worked with the fiddle.
A more proper way to do this is:
For the return date, you simply want
date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + (date.getUTCDate());
(date.getMonth
is 0-indexed while date.getDate
is 1-indexed but susceptible to time-zone differences.)
Fiddle: http://jsfiddle.net/GyC3t/25/
How to convert ViewData which is containing datetime value in it inside view(Razor) and assign to datetime picker input field(datetime-local)
<input type="datetime-local" id="fromDate" value="@(((DateTime)ViewData["fromDate"]).ToString("yyyy-MM-dd"))" />
However, if you are using ASP.NET Core, you should use a ViewModel and input tag helpers. Then you set the format string on the tag helper and it takes care of formatting the date correctly:
public class MyViewModel
{
// various properties for the view
public DateTime FromDate {get;set;}
}
Then your tag helper:
<input asp-for="FromDate" asp-format="yyyy-MM-dd" />
Note that the format must be yyyy-MM-dd
according to RFC 3339. The datetime-local control will take care of presenting the value in the locale of the user.
I've blogged here about working with DateTimes in ASP.NET Core. It's Razor Pages focused, but the principles apply to MVC too: https://www.mikesdotnetting.com/article/352/working-with-dates-and-times-in-razor-pages-forms
Display DateTime value in dd/mm/yyyy format in Asp.NET MVC
After few hours of searching, I just solved this issue with a few lines of code
Your model
[Required(ErrorMessage = "Enter the issued date.")]
[DataType(DataType.Date)]
public DateTime IssueDate { get; set; }
Razor Page
@Html.TextBoxFor(model => model.IssueDate)
@Html.ValidationMessageFor(model => model.IssueDate)
Jquery DatePicker
<script type="text/javascript">
$(document).ready(function () {
$('#IssueDate').datepicker({
dateFormat: "dd/mm/yy",
showStatus: true,
showWeeks: true,
currentText: 'Now',
autoSize: true,
gotoCurrent: true,
showAnim: 'blind',
highlightWeek: true
});
});
</script>
Webconfig File
<system.web>
<globalization uiCulture="en" culture="en-GB"/>
</system.web>
Now your text-box will accept "dd/MM/yyyy" format.
Related Topics
What Is the Correct Way to Compare Char Ignoring Case
Trying to Add Spaces Between Characters in a String in C#
Regular Expression for Password Validation in C#
How to Submit Disabled Input in ASP.NET MVC
How to Show a Console Output/Window in a Forms Application
Generate Xml for <Govtalkmessage Xmlns="Http://Www.Govtalk.Gov.Uk/Cm/Envelope">
C# ASP.NET MVC Download a File Via Ajax
C# Json.Net How to Ignore a Property in Deserialization But Not in Serialization
C# - How to Save Byte Values to File With Smallest Size Possible
Parse Strings to Double With Comma and Point
How to Get Group of Records With Latest Date Using Linq to Entities
Asp.Net Core Identity Successful Login Redirecting Back to Login Page
C# How to Check If a Url Exists/Is Valid
How to Perform Join Between Multiple Tables in Linq Lambda
How to Use a Nuget Package Within a Powershell Script
Convert Character to Its Alphabet Integer Position
How to Print the Elements With Text Value That Contains in a List Selenium C#
Response to Preflight Request Doesn't Pass Access Control Check (Angular2)