0

I don't know how to write date time in C#, more specific which is a default format of date-time. I have two classes. One is Student and the second one is DiplomiraniStudent (which means a student who gets graduated). Class student have properties ime (engl. first name), prezime (engl. last name), jmbag is a special id for students, imeObrUstanove (engl. name of an educational institution), nazivStudija (engl. name of study), datUpisStudija (engl. date when a student enrolled in study) and second class inherits first class. Second class DiplomiraniStudent has just one property which is datZavrStudija (engl. date when the student graduated). In first class I write method which return a formatted string, and in the second class, I write override method. In Program I don't know how to write date-time. It's called an error in date-time format. I don't know should I specify the format of date ore there is some format which .NET framework allready use. Here is my code.

Class Student

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Vjezba_4
{
    class Student
    {
        public string ime { get; set; }
        public string prezime { get; set; }
        public string jmbag { get; set; }
        public string imeObrUstanove { get; set; }
        public string nazivStudija { get; set; }
        public DateTime datUpisStudija { get; set; }

        public Student(string Ime, string Prezime, string Jmbag, string ImeObrUstanove, string NazivStudija, DateTime DatUpisStudija)
        {
            this.ime = Ime;
            this.prezime = Prezime;
            this.jmbag = Jmbag;
            this.imeObrUstanove = ImeObrUstanove;
            this.nazivStudija = NazivStudija;
            this.datUpisStudija = DatUpisStudija;
        }
        public Student() {}

        public virtual string PodaciOStudentu()
        {
            return String.Format(this.ime, this.prezime, this.jmbag, this.imeObrUstanove, this.nazivStudija, this.datUpisStudija);
        }
    }
}

Class Diplomirani Student

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Vjezba_4
{
    class DiplomiraniStudent:Student
    {
        public DateTime datZavrStudija { get; set; }

        public DiplomiraniStudent(string Ime, string Prezime, string Jmbag, string ImeObrUstanove, string NazivStudija, DateTime DatUpisStudija, DateTime DatZavrStudija): base(Ime, Prezime, Jmbag, ImeObrUstanove, NazivStudija, DatUpisStudija)
        {
            this.datZavrStudija = DatZavrStudija;
        }
        public DiplomiraniStudent() {}

        public override string PodaciOStudentu()
        {
            return String.Format(this.ime, this.prezime, this.jmbag, this.imeObrUstanove, this.nazivStudija, this.datUpisStudija, this.datZavrStudija);
        }
    }
}

Program

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Vjezba_4
{
    class Program
    {
        static void Main(string[] args)
        {
            Student student = new Student("Jakov", "Jaki", "549900871", "Veleučilište Velika Gorica", "Održavanje računalnih sustava", 17.07.2018);
            DiplomiraniStudent dipstudent = new DiplomiraniStudent("Mate", "Matić", "Veleučilište Velika Gorica", "Održavanje računalnih sustava", 19.07.2014, 25.06.2019);

            Console.WriteLine(student.PodaciOStudentu());
            Console.WriteLine(student.ime);
            Console.WriteLine(student.prezime);
            Console.WriteLine(student.jmbag);
            Console.WriteLine(student.imeObrUstanove);
            Console.WriteLine(student.nazivStudija);
            Console.WriteLine(student.datUpisStudija);
            Console.WriteLine();
            Console.WriteLine(dipstudent.PodaciOStudentu());
            Console.WriteLine(dipstudent.ime);
            Console.WriteLine(dipstudent.prezime);
            Console.WriteLine(dipstudent.jmbag);
            Console.WriteLine(dipstudent.imeObrUstanove);
            Console.WriteLine(dipstudent.nazivStudija);
            Console.WriteLine(dipstudent.datUpisStudija);
            Console.WriteLine(dipstudent.datZavrStudija);
        }
    }
}
  • 1
    Try `new DateTime(year, month, day etc)` [as specified in the docs](https://learn.microsoft.com/en-us/dotnet/api/system.datetime?view=netframework-4.8) – MX D Jan 08 '20 at 16:55
  • There is no Date literal in C#, which appears to be what you're looking for. – Heretic Monkey Jan 08 '20 at 16:57

4 Answers4

3

You want to use DateTime.ToString like so: DateTime.Now.ToString("MM/dd/yyyy")

A list of available formats is here.

EDIT: After seeing the constructor call you are using for Student I've concluded that you're simply not passing a DateTime; there is no shorthand way to initialize a DateTime object as there is for most number types. You need to use the actual DateTime constructor as MX D stated:

new DateTime(2018, 07, 17)

gabriel.hayes
  • 2,267
  • 12
  • 15
2

To create your students, you can use the DateTime constructor that takes in a year, month, and day:

Student student = new Student("Jakov", "Jaki", "549900871", "Veleučilište Velika Gorica", 
    "Održavanje računalnih sustava", new DateTime(2018, 7, 17));

DiplomiraniStudent dipstudent = new DiplomiraniStudent("Mate", "Matić", 
    "Veleučilište Velika Gorica", "Održavanje računalnih sustava", 
    new DateTime(2014, 7, 19), new DateTime(2019, 6, 25));

Then, when outputting the datetime as a string, you can use dat.ToShortDateString() (or dat.ToLongDateString(), or you could specify a custom string format using dat.ToString(customFormatString)).

For example:

public override string PodaciOStudentu()
{
    return $"{ime} {prezime} {jmbag} {imeObrUstanove} {nazivStudija} " + 
        $"{datUpisStudija.ToShortDateString()} {datZavrStudija.ToShortDateString()}");
}

For more information on DateTime string formats, check out Standard DateTime Format Strings and Custom DateTime Format Strings

Rufus L
  • 36,127
  • 5
  • 30
  • 43
1

In your case I recommend to use a function to convert string to date by using ParseExact and specifying the format. This helps in future if you change the format or additional formats.

private static DateTime ParseDate(string providedDate)
{
    DateTime validDate;
    string[] formats = { "dd.MM.yyyy" };
    var dateFormatIsValid = DateTime.TryParseExact(
      providedDate,
      formats,
      CultureInfo.InvariantCulture,
      DateTimeStyles.None,
      out validDate);
    return dateFormatIsValid ? validDate : DateTime.MinValue;
}

How to use

var mydate = ParseDate("17.07.2018");

In your case you should do something like

var student = new Student(....., ParseDate("17.07.2018"));
var dipstudent = new DiplomiraniStudent(...., ParseDate("19.07.2014"), ParseDate("25.06.2019"));
Krishna Varma
  • 4,238
  • 2
  • 10
  • 25
  • 1
    Why parse a string literal to create a `DateTime` when you can more efficiently use `new DateTime(2018, 7, 17)`? – Heretic Monkey Jan 08 '20 at 16:59
  • @KrishnaMuppalla Why would that be ideal? – gabriel.hayes Jan 08 '20 at 17:03
  • @HereticMonkey Why parse the string yourself into Year, Month, and Day when DateTime.Parse already does it for you? "Reinvent the wheel" is never good advice. –  Jan 08 '20 at 17:03
  • 1
    The OP is not using a string @Josh. – Heretic Monkey Jan 08 '20 at 17:04
  • @HereticMonkey, your point is right if the data comes in the form of Year, Month, and Day. But in the OP, he mentioned exact string `17.07.2018` – Krishna Varma Jan 08 '20 at 17:06
  • 1
    @HereticMonkey in this example he isn't using a DateTime or separate values for Year, Month, Day, either. This is clearly a date-time formatted string he just didn't put quotation marks around. This wont compile as is. –  Jan 08 '20 at 17:07
  • That's the OP's attempt to make a DateTime literal. Other languages have them (and indeed, C# has them for integers and other types), but not C#. To create a DateTime, one uses `new DateTime()`, passing in values to the constructor indicating the desired initial date and time. You can also create one by parsing a string, but that is unnecessary when the `DateTime` constructor has an overload which takes year, month, and day. – Heretic Monkey Jan 08 '20 at 17:12
  • In my task tells me that I need to create a method that formates to string and all properties need to be formatted into a string. I know that this makes no sense but I didn't write a task. So, in that case, should I specify date-time as DateTime ore string? Ore should I use another data type? I just know for DateTime and if I use string for date-time than method doesn't make a sense so definitely should be DatTime, if you suggest to me some other type of data I will appreciate that. – The.Strider Jan 08 '20 at 17:13
  • @The.Strider There are a lot of times when you would convert string to DateTime and vice-versa, it just depends on what you are using it for at that moment. There are many times when you are getting the string version and have to parse it to a DateTime. Thats why the DateTime.Parse and TryParse methods exist. Its a very common use case. If you decide how the data gets entered and you can provide the day, month, and year as their own units then using the constructor for DateTime makes sense. If you're stuck working from a string then you have to parse. It just depends on the form of the data –  Jan 08 '20 at 18:00
  • @The.Strider, in general what you are doing is right. To make it more generic and reusable you can adopt above code. if the format changes in future, you can change at one place – Krishna Varma Jan 09 '20 at 08:35
1

You just have to specify the correct culture info when parsing it

DateTime.Parse("17.07.2018", CultureInfo.GetCultureInfo("hr-HR"))