convert my type to string

98 views Asked by At

I have a class as:

public class PersianDate
{
    public int Year;
    public int Month;
    public int Day;
    public int Hour;
    public int Minute;
    public int Second;
    public string MonthName;
}

I want that if I convert it like here:

HTools.PersianDate pDate=new HTools.PersianDate();
string date = pDate.ToString();

And I want date to be:

1396-06-14T19:17:38

How can I do that?

2

There are 2 answers

0
Akshey Bhat On
public class PersianDate
{
    public int Year;
    public int Month;
    public int Day;
    public int Hour;
    public int Minute;
    public int Second;
    public string MonthName;

    public override string ToString()
    {
        return string.Format("{0}-{1}-{2}T{3}:{4}:{5}",Year,Month,Day,Hour,Minute,Second);
    }
}

Override ToString() method from object class to get the format you want.

DotNetFiddle Example.

2
Aviram Fireberger On

If you want a string that represent the object as a json you can use the "Newtonsift.Json" Nuget package:

PersianDate thing = new PersianDate();
//TODO: fill you thing with the data you need
string json = JsonConvert.SerializeObject(thing);

If you want specific string - ovverride the ToString methods in your class:

public override string ToString()
{
     return $"{Year}-{Month}-{Day}T{Hour}:{Minute}:{Second}";
}