开发者

How to subtract dates in YYYYMMDD format?

I have 2 integer fields that represent dates in the YYYYMMDD format. What is the best way to subtract 2开发者_运维技巧 of these fields to get the correct # of days between them?

For instance, if I take the difference between 20100511 and 20100428 I would like the result to be 13 and not 83. I know I need to convert the integer fields into date formats but everything I have tried either throws an exception or doesn't work correctly.

What am I missing? Answers in vb.net please


It should be something like this (untested!)

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


Overkill code...

// 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


    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


 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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜