VB.NET 日時を計算するサンプル(加算と減算)

VB.NETの日時を計算するサンプルです。加算と減算を行います。

目次

サンプル 日時を計算するサンプル
  TimeSpanで日時を計算するサンプル

日時を計算するサンプル

Public Structure DateTime
  Public Function AddYears(value As Integer) As DateTime
  Public Function AddMonths(months As Integer) As DateTime
  Public Function AddDays(value As Double) As DateTime
  Public Function AddHours(value As Double) As DateTime
  Public Function AddMinutes(value As Double) As DateTime
  Public Function AddSeconds(value As Double) As DateTime

日時を計算するサンプルです。

Module Module1
	Sub Main()
		'Dim dt1 As New DateTime(2020, 2, 10, 22, 30, 10) '2020/2/10 22:30:10
		Dim dt1 As New DateTime
		dt1 = Convert.ToDateTime("2020/02/10 22:30:10")

		' 3年後を求める
		Console.WriteLine(dt1.AddYears(3)) ' 2023/02/10 22:30:10

		' 3ヶ月後を求める
		Console.WriteLine(dt1.AddMonths(3)) ' 2020/05/10 22:30:10

		' 3日前を求める
		Console.WriteLine(dt1.AddDays(-3)) ' 2020/02/07 22:30:10

		' 3時間後を求める
		Console.WriteLine(dt1.AddHours(3)) ' 2020/02/11 1:30:10

		' 3分後を求める
		Console.WriteLine(dt1.AddMinutes(3)) ' 2020/02/10 22:33:10

		' 3秒後を求める
		Console.WriteLine(dt1.AddSeconds(3)) ' 2020/02/10 22:30:13

	End Sub
End Module

3行目は、指定日時に数値を指定しています。
4,5行目は、日時の文字列をDateTime型に変換しています。
日時の指定はどちらでも可能です。

年月日時分秒とそれぞれメソッドがあります。
引数にプラスの値を指定すると加算します。
減算する場合は、14行目のように引数にマイナス値を指定します。

以下は、MicrosoftのAddYearsメソッドのリンクです。
https://docs.microsoft.com/ja-jp/dotnet/api/system.datetime.addyears?view=netframework-4.8

 

TimeSpanで日時を計算するサンプル

Public Structure TimeSpan
Public Sub New(days As Integer, hours As Integer, minutes As Integer, seconds As Integer)
Public Sub New(days As Integer, hours As Integer, minutes As Integer, seconds As Integer, milliseconds As Integer)

TimeSpanで日時を計算するサンプルです。

Module Module1
	Sub Main()
		'Dim dt1 As New DateTime(2020, 2, 10, 22, 30, 10) '2020/2/10 22:30:10
		Dim dt1 As New DateTime
		dt1 = Convert.ToDateTime("2020/02/10 22:30:10")

		' 5日と30分をセット
		Dim ts1 As New TimeSpan(5, 0, 30, 0)

		' 足し算
		Dim dt2 As DateTime = dt1 + ts1
		Console.WriteLine(dt2) ' 2020/02/15 23:00:10

		'引き算
		Dim dt3 As DateTime = dt1 - ts1
		Console.WriteLine(dt3) ' 2020/02/05 22:00:10
	End Sub
End Module

3行目は、指定日時に数値を指定しています。
4,5行目は、日時の文字列をDateTime型に変換しています。
日時の指定はどちらでも可能です。

8行目は、TimeSpan構造体です。1つめの引数は日数で以降は時間、分、秒です。
例では、5日と30分を指定しています。
11行目は、足し算をして日時を求めています。
15行目は、引き算をして日時を求めています。

以下は、MicrosoftのTimeSpan構造体のリンクです。
https://docs.microsoft.com/ja-jp/dotnet/api/system.timespan?view=netframework-4.8

関連の記事

VB.NET 現在日時の取得と表示形式のサンプル

△上に戻る