Convert String to Date and Add ±N Hours

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Nov 4 19:19:43 UTC 2023


On Saturday, November 4, 2023 12:11:53 PM MDT Vahid via Digitalmars-d-learn 
wrote:
> Hi,
>
> I have a date string with the format of "2023-11-04 23:10:20". I
> want to convert this string to Date object and also, add ±N hours
> to it. For example:
>
> `"2023-11-04 23:10:20" + "+2:00" = "2023-11-05 01:10:20"`
> `"2023-11-04 23:10:20" + "-2:30" = "2023-11-05 20:40:20"`
>
> How can I do this?

If you're using D's standard library, you would need to replace the space
with a T so that the time format was ISO extended. Then you can use
DateTime.fromISOEXtString() in std.datetim.date to get a DateTime. You can
then add a duration to the DateTime to change its value - e.g. using
hours(2) (or dur!"hours"(2) for the generic version). Then if you want
a string again, toISOExtString will convert the DateTime to the ISO extended
format, and if you want a space instead of a T, then just replace the T with
a space in the string. E.G.

import core.time : hours;
import std.array : replace;
import std.datetime.date : DateTime;

auto dt = DateTime.fromISOExtString(strBefore.replace(' ', 'T'));
dt += hours(2);
auto strAfter = dt.toISOExtString().replace('T', ' ');

However, if you also need to convert a string like "+2:00" to a Duration,
then you'll need to create a function like that yourself. If you already
have an integer value though, then you can just create a Duration and add it
to the DateTime.

At present D's standard library just supports the ISO standard, ISO extended
standard, and Boost's "simple" format for converting dates and times to and
from strings. And it doesn't support any format for converting from strings
to Durations. There are third party libraries on code.dlang.org which
support custom formatting for dates and times (e.g.
https://code.dlang.org/packages/ae), but I'm not familiar enough with any of
them to tell you how to solve your problem with them. That being said, since
you seem to haves strings that are almost in the ISO extendend format, it
should be pretty easy to get them to work with D's standard library.

- Jonathan M Davis






More information about the Digitalmars-d-learn mailing list