0

Is yyyy a valid format for DateTime? I want to store only the year. As mvc model throws an error that yyyy is not valid format for datetime.

[DisplayName("Year Obtained")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy}", ApplyFormatInEditMode = true)]
public DateTime reDateFrom { get; set; }
DavidG
  • 113,891
  • 12
  • 217
  • 223
Ejazkhan
  • 11
  • 3
  • 3
    http://stackoverflow.com/questions/696506/sql-datatype-how-to-store-a-year answers your question:) – Roman Jun 14 '16 at 00:27
  • The `DisplayFormat` attribute will only affect the display format when using methods like `Html.DisplayFor`, not the database format. – DavidG Jun 14 '16 at 00:29
  • how to set year in database format? – Ejazkhan Jun 14 '16 at 00:33
  • 2
    If you want to store 4-digit year instead of full date, use int data type on SQL. Date & DateTime should be used for full date (and time) format. – Tetsuya Yamamoto Jun 14 '16 at 01:05

2 Answers2

0

You can do one thing in the model you can put the type as int as the year part is a integer type you need the change the type in database too.

or you can put the type as string in the model and in the controller while storing you can do this

    string dateTime = DateTime.UtcNow.ToString("yyyy");

which will store the year part only

Sai Chaitanya
  • 195
  • 1
  • 1
  • 13
0

You have to store an Int type for the year into Database.

Or if you want to leave Datetime type into database you can create a MetaData class in Models MVC, then create a new Int property "Year Obtained", please see below:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace YourWebApp.Models
{
    [MetadataType(typeof(YourClassMetaData))]
    public partial class YourClass
    {
        [DisplayName("Year Obtained")]
        public int YYObtained {
            get
            {
                return this.reDateFrom.Year;
            }
        }
    }

    public class YourClassMetaData
    {
        [DataType(DataType.Date)]
        public DateTime reDateFrom { get; set; }
    }
}
SturDs
  • 11
  • 3