关于以字符串格式使用日期时间

时间:2017-06-04 22:35:01

标签: c# visual-studio

我正在试图弄清楚如何从今天的日期中减去日期时间,但每当我输入注册日期时,它会持续很长时间。这是我到目前为止的代码

    public string getTimeAsStudent(DateTime EnrolledDate)
    {
        return DateTime.Today.Subtract(EnrolledDate).ToString();

    }

    public string getTimeAsStudent()
    {
        return DateTime.Today.Subtract(oEnrolledDate).TotalDays.ToString();

    }

以下是我对测试应用程序的了解

 namespace StudentTestApp
   {
    public partial class Form1 : Form
    {
    public Form1()
    {
        InitializeComponent();
    }

    Student.StudentGrades myStudent = new Student.StudentGrades();

    private void getDate_Click(object sender, EventArgs e)
    {
        lblDate.Text = myStudent.getTimeAsStudent().ToString();
    }
}

辅助变量

   public class StudentGrades
   {
    private string oStudentFirstName;
    private string oStudentMiddleName;
    private string oStudentLastName;
    private string oStudentID;
    private string oAddress;
    private string oEmail;
    private DateTime oEnrolledDate;
    private string oMajor;
    private string oPhone;
    private string oZip;
    private List<string> oCourseCompleted;
    private List<string> oCourseQtrYr;
    private List<double> oCourseGrade;

然而无论我投入的日期如何,它都输出了736,000天,任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

这是Subtract方法的类型

如何减去两个DateTime到年

public static string getTimeAsYear(DateTime oEnrolledDate)
{
        return (Math.Abs(oEnrolledDate.Year - DateTime.Today.Year)).ToString();
}

如何减去两个DateTime到月

public static string getTimeAsMonth(DateTime oEnrolledDate)
{
        return ((Math.Abs(oEnrolledDate.Year - DateTime.Today.Year)) * 12).ToString();
}

结果

DateTime D = new DateTime(1995,01,17); Console.WriteLine(getTimeAsStudent(D)); Console.WriteLine(getTimeAsYear(D)); Console.WriteLine(getTimeAsMonth(D));

enter image description here