Nullbyte
Nullbyte

Reputation: 241

Add 10 hours to server time

In a winform I have a string that rapresent a serial number and it is made up as following:

PR (which is a prefix) + ss mm hh dd mm yy

which results in something like PR010110120914. Now this is the server time on which a record was saved. This is my code where rawDate is the above string from the DB:

string datetimeinserver = DateTime.ParseExact(rawDate.Substring(2),
            "ssmmHHddMMyy",
            CultureInfo.InvariantCulture)
                .ToString("HH:mm:ss on dd/MM/yyy");

For various reasons I need to add 10 hours to datetimeinserver, I have messed around without results. Is there a simple way to add 10 hours to datetimeinserver?

Upvotes: 0

Views: 86

Answers (3)

Habib
Habib

Reputation: 223187

DateTime.ParseExact would return you a DateTime object. You can then use DateTime.AddHours method like:

DateTime tempDt = DateTime.ParseExact(rawDate.Substring(2),
                  "ssmmHHddMMyy",
                   CultureInfo.InvariantCulture);

tempDt = tempDt.AddHours(10);

string datetimeinserver = tempDt.ToString("HH:mm:ss on dd/MM/yyy");

You can also do the same in one statement like:

string datetimeinserver = DateTime.ParseExact(rawDate.Substring(2),
            "ssmmHHddMMyy",
            CultureInfo.InvariantCulture)
            .AddHours(10)
                .ToString("HH:mm:ss on dd/MM/yyy");

Upvotes: 1

Pedro
Pedro

Reputation: 1124

string datetimeinserver = DateTime.ParseExact(rawDate.Substring(2),"ssmmHHddMMyy", CultureInfo.InvariantCulture);

dateTimeinserver.AddHours(10).ToString("HH:mm:ss on dd/MM/yyy");

?

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 156898

Use DateTime.AddHours for that. Just change your code to this:

DateTime dt = DateTime.ParseExact(rawDate.Substring(2),
        "ssmmHHddMMyy",
        CultureInfo.InvariantCulture);
dt = dt.AddHours(10);
string datetimeinserver = dt.ToString("HH:mm:ss on dd/MM/yyy");

Upvotes: 3

Related Questions