在Ubuntu上進行Fortran程序的時間和日期處理,你可以使用Fortran 90或更高版本中提供的標準庫模塊iso_fortran_env和date_and_time。以下是一個簡單的例子,展示了如何在Fortran程序中獲取當前的時間和日期:
program datetime_example
use iso_fortran_env, only: real64
use date_and_time, only: get_date, get_time, current_date, current_time, set_date, set_time
character(len=10) :: date_str
character(len=8) :: time_str
integer :: values(8)
real(real64) :: seconds_since_epoch
! 獲取當前日期和時間
call get_date(date_str)
call get_time(time_str)
print *, 'Current date:', date_str
print *, 'Current time:', time_str
! 將日期轉換為整數數組
read(date_str, '(I2, I2, I2)') values
print *, 'Date as integer array:', values
! 將時間轉換為整數數組
read(time_str, '(I2, I2, I2)') values
print *, 'Time as integer array:', values
! 獲取自某個時間點以來的秒數(例如,自0001-01-01以來的秒數)
call current_date(date_str)
call current_time(time_str)
read(date_str, '(I4, I2, I2)') values(1:3)
read(time_str, '(I2, I2, I2)') values(4:6)
seconds_since_epoch = (values(1) - 1) * 31536000 + &
values(2) * 2592000 + &
values(3) * 86400 + &
values(4) * 3600 + &
values(5) * 60 + &
values(6)
print *, 'Seconds since epoch:', seconds_since_epoch
! 設置日期和時間
call set_date('2023-01-01')
call set_time('12:00:00')
! 再次獲取日期和時間以確認更改
call get_date(date_str)
call get_time(time_str)
print *, 'New date:', date_str
print *, 'New time:', time_str
end program datetime_example
在這個例子中,我們首先使用get_date和get_time子程序獲取當前的日期和時間,并將它們打印出來。然后,我們將日期和時間轉換為整數數組,并打印這些數組。接著,我們計算自0001-01-01以來的秒數,并打印這個值。最后,我們使用set_date和set_time子程序設置一個新的日期和時間,并再次獲取它們以確認更改。
要編譯這個Fortran程序,你可以使用gfortran編譯器。在終端中,輸入以下命令:
gfortran -o datetime_example datetime_example.f90
然后運行生成的可執行文件:
./datetime_example
請注意,這個例子使用了Fortran 2003標準中的date_and_time模塊,因此你需要確保你的編譯器支持這個標準或更高版本。如果你使用的是較舊的Fortran編譯器,可能需要查找特定于該編譯器的日期和時間處理方法。