我需要从2015年减去一年(比方说1991年),使用c#
本文关键字:一年 1991年 使用 2015年 | 更新日期: 2023-09-27 18:10:51
几个小时以来,我一直在寻找这个非常简单的代码的解决方案。我昨天开始了我的编程生涯,今天得到了Visual Studio。我试过玩"你好世界"的练习,但从彼此身上扣除两年的时间比我想象的要困难得多。
我的代码确实显示了我目前的水平,我恳求你们,我到底做错了什么?
using System;
namespace HelloWorld
{
class Hello
{
static void Main()
{
Console.WriteLine("Hello World!");
// Keep the console window open in debug mode.
Console.Write("Please enter your first name: ");
string firstName = Console.ReadLine();
Console.Write("Please enter your last name: ");
string lastName = Console.ReadLine();
Console.WriteLine("");
Console.WriteLine("You're Name is: " + firstName + " " + lastName);
Console.WriteLine("");
Console.WriteLine("Please enter your birthyear");
Console.WriteLine("");
string yob = Console.ReadLine();
Console.WriteLine("");
Console.WriteLine("Today it's...");
DateTime time = DateTime.Now; // Use current time.
string format = "yyyy"; // Use this format. (MMM ddd d HH:mm yyyy)
Console.WriteLine(time.ToString(format)); // Write to console.
Console.WriteLine(" ");
Console.WriteLine("Which means that you are approximately....");
Console.WriteLine("?? Years old");
//timespan between `datenow` and `date1`
Console.ReadKey();
}
}
}
将yob
转换为int:
int yearOfBirth = int.Parse(yob); //This could fail! See note below
然后从今天的年份中减去:
int yearsOld = DateTime.Now.Year - yearOfBirth;
Console.WriteLine(yearsOld + " years old");
注意:如果输入的不是数字,例如two thousand
,则int.Parse
命令可能会失败。查看int.TryParse
以处理这种情况。
// get current time
DateTime now = DateTime.Now;
// get year of birth from user
String myYear = Console.ReadLine();
// construct a DateTime from that year
DateTime my = new DateTime(Convert.ToInt16(myYear), 1, 1);
// devide by 365 and convert to int
Console.Write(Convert.ToInt16((now - my).TotalDays) / 365);
System.TimeSpan将帮助您计算差异。快速搜索"日期差异c#"得到了这个代码。如果你想了解更多,页面上有多种方法。如果你需要更多的帮助,请告诉我。
using System;
using System.Collections.Generic;
using System.Text;
namespace Console_DateTime
{
class Program
{
static void Main(string[] args)
{
System.DateTime dtTodayNoon = new System.DateTime(2006, 9, 13, 12, 0, 0);
System.DateTime dtTodayMidnight = new System.DateTime(2006, 9, 13, 0, 0, 0);
System.TimeSpan diffResult = dtTodayNoon.Subtract(dtYestMidnight);
Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.Days);
Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.TotalDays);
Console.ReadLine();
}
}
}
来源:c-sharpcorner.com
编辑:忘记了解释的第一行。