development

날짜 만 표시하고 시간은 표시하지 않음

big-blog 2020. 9. 10. 08:14
반응형

날짜 만 표시하고 시간은 표시하지 않음


MVC 면도기에서는 이와 같이 데이터베이스에 현재 날짜를 넣습니다.

model.Returndate = DateTime.Now.Date.ToShortDateString();

데이터베이스 필드가 datetime 데이터 유형이고 현재 날짜를 문자열 형식으로 변환하고 있기 때문에 작동하지 않습니다. 어떻게해야합니까? 날짜를 mm / dd / yyyy hh : mm : ss 시간 형식이 아닌 mm / dd / yyyy 형식으로 원하기 때문에 문자열 형식을 사용하고 있습니다.

편집하다:

컨트롤러에는

var model = new ViewModel();
model.ReturnDate = DateTime.Now;            
return PartialView("PartialView", model);  

부분보기에서 나는

@Html.EditorFor(model => model.Returndate)

이것은 날짜와 시간을 함께 표시하는 곳입니다. 날짜 만 표시하고 싶습니다. 시간이 아닙니다. 이 편집이 더 잘 설명되기를 바랍니다.


열 유형이 SQL에서 DateTime이면 통과 여부를 저장합니다.

날짜를 제대로 저장하는 것이 좋습니다.

model.ReturnDate = DateTime.Now;

표시해야 할 때 형식을 지정합니다.

@Html.Label(Model.ReturnDate.ToShortDateString())

또는 EditorFor를 사용하는 경우 :

@Html.EditorFor(model => model.ReturnDate.ToShortDateString())

또는

@Html.EditorFor(model => model.ReturnDate.ToString("MM/dd/yyyy"))

모델에 속성을 추가하려면 다음 코드를 추가하세요.

public string ReturnDateForDisplay
{
    get
    {
       return this.ReturnDate.ToString("d");
    }
}

그런 다음 PartialView에서 :

@Html.EditorFor(model => model.ReturnDateForDisplay)

편집하다:

안녕하세요 여러분,이 답변에 대해 'If you 're using EditorFor'라는 말로 표현하려는 값 유형에 대한 EditorFor 템플릿이 필요하다는 것을 명확히하고 싶습니다.

편집기 템플릿은 MVC에서 반복적 인 컨트롤을 관리하는 멋진 방법입니다.

http://coding-in.net/asp-net-mvc-3-how-to-use-editortemplates/

위에서 한 것처럼 String과 같은 순진한 유형에 사용할 수 있습니다. 그러나 더 복잡한 데이터 유형에 대한 입력 필드 세트를 템플릿으로 만드는 데 특히 유용합니다.


이 시나리오를 직접 처리해야했습니다.이 작업을 수행하는 정말 쉬운 방법을 찾았습니다. 다음과 같이 모델에 속성에 주석을 달기 만하면됩니다.

[DataType(DataType.Date)]
public DateTime? SomeDateProperty { get; set; }

날짜 선택기에서도 시간 버튼을 숨 깁니다.

이 답변이 조금 늦으면 죄송합니다.)


TextBox에 표시하려는 경우 작동합니다.

@Html.TextBoxFor(m => m.Employee.DOB, "{0:dd-MM-yyyy}")

날짜 기반의 날짜 / 시간은 형식화 된 버전 이 아닙니다 . 날짜 / 시간 자체 일뿐입니다. 데이터베이스에서 값을 추출 할 때 해당 날짜 / 시간 표시 하는 방법 은 다른 문제입니다. 나는 당신이 정말로 원하는 것을 강력히 의심합니다.

model.Returndate = DateTime.Now.Date;

또는 아마도

model.Returndate = DateTime.UtcNow.Date;

당신은 SQL 서버 스튜디오 또는 무엇이든을 사용하여 데이터베이스를 보면 예, 당신은 지금 자정를 볼 수 있습니다 -하지만 관련이없는, 그리고 데이터베이스의 날짜를 가져오고 사용자에게 표시 할 때, 다음 당신은 관련 서식을 적용 할 수 있습니다 .

편집 : 편집 한 질문과 관련하여 문제는 모델에있는 것이 아니라보기를 지정하는 방법입니다. 다음과 같은 것을 사용해야합니다.

@Html.EditorFor(model => model.Returndate.Date.ToString("d"))

where d is the standard date and time format specifier for the short date pattern (which means it'll take the current cultural settings into account).

That's the bit I've been saying repeatedly - that when you display the date/time to the user, that's the time to format it as a date without a time.

EDIT: If this doesn't work, there should be a way of decorating the model or view with a format string - or something like that. I'm not really an MVC person, but it feels like there ought to be a good way of doing this declaratively...


You can modify your ViewModel as below:

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",ApplyFormatInEditMode = true)]

You can apply custom date time format using ToString like:

DateTime.Now.Date.ToString("MM/dd/yyyy");

Further reading on DateTime.ToString formats pattern can be found here and here.

Edit: After your question edit, Just like what other suggested you should apply the date format at your view:

model.Returndate = DateTime.Now.Date;

@Html.EditorFor(model => model.Returndate.Date.ToString("MM/dd/yyyy"))

I am not sure in Razor but in ASPX you do:

 <%if (item.Modify_Date != null)
  {%>
     <%=Html.Encode(String.Format("{0:D}", item.Modify_Date))%>     
<%} %>

There must be something similar in Razor. Hopefully this will help someone.


If you have a for loop such as the one below.

Change @item.StartDate to @item.StartDate.Value.ToShortDateString()

This will remove the time just in case you can't annotate your property in the model like in my case.

<table>
  <tr>
   <th>Type</th>
   <th>Start Date</th>
  </tr>
    @foreach (var item in Model.TestList) {
      <tr>
        <td>@item.TypeName</td>
        <td>@item.StartDate.Value.ToShortDateString()</td>
      </tr>
      }
</table>

[Display(Name = "Bill Date")] [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] public DateTime BillDate { get; set; }

Now your Bill date will show like.

enter image description here


You could simply convert the datetime. Something like:

@Convert.ToString(string.Format("{0:dd/MM/yyyy}", Model.Returndate))

I had some problems with the other solutions on this page, so thought I'd drop this in.

@Html.TextBoxFor(m => m.EndDate, "{0:d}", new { @class = "form-control datepicker" })

So you only need to add "{0:d}" in the second parameter and you should be good to go.

참고URL : https://stackoverflow.com/questions/7124434/display-only-date-and-no-time

반응형