我有2个整数字段,表示YYYYMMDD格式的日期。减去其中2个字段以获得它们之间正确的天数的最佳方法是什么?
例如,如果我采用20100511和20100428之间的差异,我希望结果为13而不是83.我知道我需要将整数字段转换为日期格式,但我尝试的所有内容都会抛出异常或不工作正常。
我错过了什么?请访问vb.net中的答案
答案 0 :(得分:8)
它应该是这样的(未经测试!)
Dim date1 As DateTime = DateTime.ParseExact(yourdate1.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture)
Dim date2 As DateTime = DateTime.ParseExact(yourdate2.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture)
Dim days As Integer = date1.Subtract(date2).Days
答案 1 :(得分:4)
过度杀伤代码......
// C#
var ds1 = 20100511;
var ds2 = 20100428;
Func<int, DateTime> getDate = s => DateTime.ParseExact(s.ToString(),
"yyyyMMdd",
null);
var d1 = getDate(ds1);
var d2 = getDate(ds2);
var diff = d1.Subtract(d2);
var result = diff.Days; //13
...
//VB.Net
Dim ds1 = 20100511
Dim ds2 = 20100428
Dim getDate = Function(s) DateTime.ParseExact(s.ToString(), "yyyyMMdd", Nothing)
Dim d1 = getDate(ds1)
Dim d2 = getDate(ds2)
Dim diff = d1.Subtract(d2)
Dim result = diff.Days '13
答案 2 :(得分:2)
Dim dt1 As Integer = 20100510
Dim dt2 As Integer = 20100520
Dim date1 As DateTime = DateTime.ParseExact(dt1.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture)
Dim date2 As DateTime = DateTime.ParseExact(dt2.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture)
Dim nDays As Integer = date1.Subtract(date2).Days
答案 3 :(得分:0)
DateTime x = DateTime.ParseExact("19920715", "yyyyMMdd",CultureInfo.InvariantCulture);
DateTime y = DateTime.ParseExact("20141025", "yyyyMMdd", CultureInfo.InvariantCulture);
int days = (y.Subtract(x).Days);
float years = days / 365;