プログラミング言語の比較 > 数値、日時

数値

指定された値の2乗を返す関数

Java

  1. public static int square(int x) {
  2. return x * x;
  3. }

Groovy

  1. def square(x) { x ** 2 }

Kotlin

  1. fun square(x: Int) = x * x // 戻り値の型は Int
  1. fun square(x: Int): Int { return x * x }

Scala

  1. def square(x: Int) = x * x // 戻り値の型は Int
  1. def square(x: Int): Int = { x * x }

Erlang

  1. square(X) -> X * X.

Haskell

  1. square = (^ 2)
  1. square x = x ^ 2

PowerShell

  1. function square($x) {
  2. $x * $x
  3. }
  1. function square {
  2. param($x)
  3. $x * $x
  4. }
  1. function square {
  2. $args[0] * $args[0]
  3. }

F#

  1. let square x = pown x 2 // x の型は int、戻り値の型も int
  1. let square (x : int64) = pown x 2 // 戻り値の型も int64

C#

C# 6.0以降
  1. public static int Square(int x) => x * x;

C++

  1. #include <math.h>
  2. double square(const double x) {
  3. return pow(x, 2);
  4. }

Go

  1. // import "math"
  2. func square(x float64) float64 {
  3. return math.Pow(x, 2)
  4. }

Rust

  1. pub fn square(n: i32) -> i32 {
  2. n * n
  3. }

Dart

  1. // import 'dart:math';
  2. num square(num x) => pow(x, 2);
  1. // import 'dart:math';
  2. num square(num x) {
  3. return pow(x, 2);
  4. }

TypeScript

  1. function square(x) {
  2. return Math.pow(x, 2);
  3. }

JavaScript

  1. function square(x) {
  2. return Math.pow(x, 2);
  3. }

CoffeeScript

  1. square = (x) -> Math.pow x, 2

Ruby

  1. def square x
  2. x ** 2
  3. end

Python

  1. def square(x):
  2. return x ** 2
  1. def square(x):
  2. return pow(x, 2)

PHP

  1. function square($x) {
  2. return $x ** 2;
  3. }

Perl

  1. sub square {
  2. my $x = shift;
  3. $x ** 2;
  4. }
  1. sub square {
  2. shift() ** 2;
  3. }

誤差のない四則演算

0.1×3-0.3=0.0 だが、2進数で計算すると誤差が出て 5.551115123125783e-17 になってしまう。 ここでは、その誤差を避ける計算方法を挙げる。

Java

  1. // import java.math.BigDecimal;
  2. BigDecimal result = new BigDecimal("0.1").multiply(new BigDecimal(3)).subtract(new BigDecimal("0.3"));
  3. double d = result.doubleValue();

Groovy

  1. def result = 0.1 * 3 - 0.3 // 接尾辞のない小数リテラルは BigDecimal
  2. double d = result

Kotlin

  1. // import java.math.BigDecimal
  2. val result = BigDecimal("0.1") * 3.toBigDecimal() - BigDecimal("0.3")
  3. val d = result.toDouble()

Scala

  1. val result = BigDecimal("0.1") * 3 - BigDecimal("0.3")
  2. val d = result.doubleValue

Haskell

分数を表す型を使う
  1. -- import Ratio
  2. let result = (1 % 10) * 3 - (3 % 10)
  3. let d = fromRational result

PowerShell

  1. $result = [decimal] 0.1 * 3 - [decimal] 0.3
  2. $d = [double] $result

F#

  1. let result = 0.1M * 3M - 0.3M // "M" を付けたリテラルは decimal
  2. let f = float result
F# PowerPack を使った場合
分数を表す型を使う
  1. let result = (1N / 10N) * 3N - (3N / 10N) // "N" を付けたリテラルは BigRational
  2. let f = float result

C#

  1. decimal result = 0.1M * 3 - 0.3M; // "M" を付けたリテラルは decimal
  2. double d = (double)result;

C++

Boost を使った場合
分数を表す型を使う
  1. #include <boost/rational.hpp>
  2. boost::rational<int> result = boost::rational<int>(1, 10) * 3 - boost::rational<int>(3, 10); // (1÷10)×3-(3÷10)
  3. double d = boost::rational_cast<double>(result);

Go

分数を表す型を使う
  1. // import "math/big"
  2. mul := big.NewRat(0, 0).Mul(big.NewRat(1, 10), big.NewRat(3, 1)) // mul = (1÷10)×(3÷1)
  3. result := big.NewRat(0, 0).Sub(mul, big.NewRat(3, 10)) // result = mul-(3÷10)
  4. f := float(result.Num().Int64()) / float(result.Denom().Int64())

Ruby

  1. # require 'bigdecimal'
  2. result = BigDecimal('0.1') * 3 - BigDecimal('0.3')
  3. f = result.to_f

Python

  1. # from decimal import Decimal
  2. result = Decimal('0.1') * 3 - Decimal('0.3')
  3. f = float(result)

PHP

  1. bcscale(1); // デフォルトの精度を小数第1位までにする
  2. $result = bcsub(bcmul('0.1', '3'), '0.3');
  3. $f = (float)$result;

Perl

  1. # use Math::BigFloat;
  2. my $result = Math::BigFloat->new('0.1') * 3 - Math::BigFloat->new('0.3');

代金の割引計算

Java

  1. // import java.math.*;
  2. BigDecimal unitPrice = new BigDecimal(480); // 単価:480円
  3. int buyCount = 3; // 購入数
  4. BigDecimal discountRate = new BigDecimal("0.06"); // 割引率:6%
  5. long postageExemptionCondition = 1500; // 割引後の代金が1500円以上なら送料を免除
  6. BigDecimal postage = new BigDecimal(300); // 送料:300円
  7. BigDecimal sum = unitPrice.multiply(new BigDecimal(buyCount)); // 割引前の代金
  8. sum = sum.multiply(BigDecimal.ONE.subtract(discountRate)); // 割引後の代金
  9. sum = sum.setScale(0, RoundingMode.DOWN); // 端数は切り捨て
  10. if (sum.compareTo(new BigDecimal(postageExemptionCondition)) < 0) {
  11. sum = sum.add(postage); // 送料を加算
  12. }

Groovy

  1. // import java.math.RoudingMode
  2. def unitPrice = 480 // 単価:480円
  3. def buyCount = 3 // 購入数
  4. def discountRate = 0.06 // 割引率:6%
  5. def postageExemptionCondition = 1500 // 割引後の代金が1500円以上なら送料を免除
  6. def postage = 300 // 送料:300円
  7. def sum = unitPrice * buyCount * (1 - discountRate) // 割引後の代金
  8. sum = sum.setScale(0, RoundingMode.DOWN) // 端数は切り捨て
  9. if (sum < postageExemptionCondition) {
  10. sum += postage // 送料を加算
  11. }

Kotlin

  1. // import java.math.*
  2. val unitPrice = 480 // 単価:480円
  3. val buyCount = 3 // 購入数
  4. val discountRate = BigDecimal("0.06") // 割引率:6%
  5. val postageExemptionCondition = 1500 // 割引後の代金が1500円以上なら送料を免除
  6. val postage = 300 // 送料:300円
  7. var sum = BigDecimal(unitPrice * buyCount) // 割引前の代金
  8. sum *= BigDecimal(1) - discountRate // 割引後の代金
  9. sum = sum.setScale(0, RoundingMode.DOWN) // 端数は切り捨て
  10. if (sum < postageExemptionCondition.toBigDecimal()) {
  11. sum += postage.toBigDecimal() // 送料を加算
  12. }

Scala

  1. val unitPrice = 480 // 単価:480円
  2. val buyCount = 3 // 購入数
  3. val discountRate = BigDecimal("0.06") // 割引率:6%
  4. val postageExemptionCondition = 1500 // 割引後の代金が1500円以上なら送料を免除
  5. val postage = 300 // 送料:300円
  6. var sum = BigDecimal(unitPrice * buyCount) // 割引前の代金
  7. sum *= BigDecimal(1) - discountRate // 割引後の代金
  8. sum = sum.setScale(0, BigDecimal.RoundingMode.ROUND_DOWN) // 端数は切り捨て
  9. if (sum < postageExemptionCondition) {
  10. sum += postage // 送料を加算
  11. }

Haskell

  1. -- import Ratio
  2. let unitPrice = 480 -- 単価:480円
  3. let buyCount = 3 -- 購入数
  4. let discountRate = 6 % 100 -- 割引率:6%
  5. let postageExemptionCondition = 1500 -- 割引後の代金が1500円以上なら送料を免除
  6. let postage = 300 -- 送料:300円
  7. let sum = truncate $ fromRational $ unitPrice * buyCount * (1 - discountRate) -- 割引後の代金(端数は切り捨て)
  8. let sum' = sum + (if sum < postageExemptionCondition then postage else 0) -- 送料を加算
State モナドを使う
  1. -- import Control.Monad.State
  2. -- import Ratio
  3. trunc = (% 1) . truncate . fromRational
  4. modifyIf f g = get >>= \ state -> if f state then put (g state) else return ()
  1. let unitPrice = 480 -- 単価:480円
  2. let buyCount = 3 -- 購入数
  3. let discountRatio = 6 % 100 -- 割引率:6%
  4. let postageExemptionCondition = 1500 -- 割引後の代金が1500円以上なら送料を免除
  5. let postage = 300 -- 送料:300円
  6. let (_, sum) = runState (do
  7. put unitPrice -- まず単価をセットする
  8. modify (* buyCount) -- 購入数を掛ける
  9. modify (* (1 - discountRatio)) -- 割引
  10. modify trunc -- 端数を切り捨て
  11. modifyIf (< postageExemptionCondition) (+ postage) -- 割引後の代金が1500円未満なら送料を加算
  12. ) 0
  13. let sum' = numerator sum

PowerShell

  1. $unitPrice = 480 # 単価:480円
  2. $buyCount = 3 # 購入数
  3. $discountRate = [decimal] 0.06 # 割引率:6%
  4. $postageExemptionCondition = 1500 # 割引後の代金が1500円以上なら送料を免除
  5. $postage = 300 # 送料:300円
  6. $sum = $unitPrice * $buyCount * (1 - $discountRate) # 割引後の代金
  7. $sum = [Math]::Truncate($sum) # 端数は切り捨て
  8. if ($sum -lt $postageExemptionCondition) {
  9. $sum += $postage # 送料を加算
  10. }

F#

  1. let unitPrice = 480M // 単価:480円
  2. let buyCount = 3M // 購入数
  3. let discountRate = 0.06M // 割引率:6%
  4. let postageExemptionCondition = 1500M // 割引後の代金が1500円以上なら送料を免除
  5. let postage = 300M // 送料:300円
  6. let mutable sum = unitPrice * buyCount * (1M - discountRate) // 割引後の代金
  7. sum <- System.Math.Truncate sum // 端数は切り捨て
  8. if sum < postageExemptionCondition then
  9. sum <- sum + postage // 送料を加算

C#

  1. int unitPrice = 480; // 単価:480円
  2. int buyCount = 3; // 購入数
  3. decimal discountRate = 0.06M; // 割引率:6%
  4. int postageExemptionCondition = 1500; // 割引後の代金が1500円以上なら送料を免除
  5. int postage = 300; // 送料:300円
  6. decimal sum = unitPrice * buyCount * (1 - discountRate); // 割引後の代金
  7. sum = Math.Truncate(sum); // 端数は切り捨て
  8. if (sum < postageExemptionCondition) {
  9. sum += postage; // 送料を加算
  10. }

Go

  1. // import "math/big"
  2. unitPrice := 480 // 単価
  3. buyCount := 3 // 購入数
  4. discountRate := big.NewRat(6, 100) // 割引率:6%
  5. postageExemptionCondition := 1500 // 割引後の代金が1500円以上なら送料を免除
  6. postage := 300 // 送料:300円
  7. sumRat := big.NewRat(int64(unitPrice * buyCount), 1) // 割引前の代金
  8. rateRat := big.NewRat(0, 0).Sub(big.NewRat(1, 1), discountRate)
  9. sumRat = big.NewRat(0, 0).Mul(sumRat, rateRat) // 割引後の代金
  10. sum := int(sumRat.Num().Int64() / sumRat.Denom().Int64()) // 端数は切り捨て
  11. if sum < postageExemptionCondition {
  12. sum += postage // 送料を加算
  13. }

Ruby

  1. # require 'bigdecimal'
  2. unit_price = 480 # 単価:480円
  3. buy_count = 3 # 購入数
  4. discount_rate = BigDecimal('0.06') # 割引率:6%
  5. postage_exemption_condition = 1500 # 割引後の代金が1500円以上なら送料を免除
  6. postage = 300 # 送料:300円
  7. sum = unit_price * buy_count * (1 - discount_rate) # 割引後の代金
  8. sum = sum.floor.to_i # 端数は切り捨て
  9. sum += postage if sum < postage_exemption_condition # 送料を加算

Python

  1. # from decimal import Decimal, ROUND_DOWN
  2. unit_price = 480 # 単価:480円
  3. buy_count = 3 # 購入数
  4. discount_rate = Decimal('0.06') # 割引率:6%
  5. postage_exemption_condition = 1500 # 割引後の代金が1500円以上なら送料を免除
  6. postage = 300 # 送料:300円
  7. sum = unit_price * buy_count * (1 - discount_rate) # 割引後の代金
  8. sum = sum.to_integral_value(ROUND_DOWN) # 端数は切り捨て
  9. if sum < postage_exemption_condition:
  10. sum += postage # 送料を加算

PHP

  1. bcscale(2); // デフォルトの精度を小数第2位までにする
  2. $unit_price = 480; // 単価:480円
  3. $buy_count = 3; // 購入数
  4. $discount_rate = '0.06'; // 割引率:6%
  5. $postage_exemption_condition = 1500; // 割引後の代金が1500円以上なら送料を免除
  6. $postage = 300; // 送料:300円
  7. $sum = $unit_price * $buy_count;
  8. $sum = (int)bcmul((string)$sum, bcsub('1', $discount_rate)); // 割引後の代金(端数は切り捨て)
  9. if ($sum < $postage_exemption_condition) {
  10. $sum += $postage; // 送料を加算
  11. }

Perl

  1. # use Math::BigFloat;
  2. # use Math::Round;
  3. my $unit_price = 480; # 単価:480円
  4. my $buy_count = 3; # 購入数
  5. my $discount_rate = Math::BigFloat->new('0.06'); # 割引率:6%
  6. my $postage_exemption_condition = 1500; # 割引後の代金が1500円以上なら送料を免除
  7. my $postage = 300; # 送料:300円
  8. my $sum = Math::BigFloat->new($unit_price * $buy_count); # 割引前の代金
  9. $sum *= 1 - $discount_rate; # 割引後の代金
  10. $sum->ffround(0); # 端数は切り捨て
  11. $sum += $postage if $sum < $postage_exemption_condition; # 送料を加算

日時

現在の2時間半前の時刻を文字列で表す

Java

  1. // import java.time.LocalDateTime;
  2. // import java.time.format.DateTimeFormatter;
  3. LocalDateTime dt = LocalDateTime.now().minusHours(2).minusMinutes(30);
  4. String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt);
  1. // import java.time.*;
  2. // import java.time.format.DateTimeFormatter;
  3. LocalDateTime dt = LocalDateTime.now().minus(Duration.ofHours(2).plusMinutes(30));
  4. String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt);
  1. // import java.time.*;
  2. // import java.time.format.DateTimeFormatter;
  3. // import java.time.temporal.ChronoUnit;
  4. LocalDateTime dt = LocalDateTime.now().minus(Duration.of(150, ChronoUnit.MINUTES));
  5. String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt);
  1. // import java.time.*;
  2. // import java.time.format.DateTimeFormatter;
  3. LocalDateTime dt = LocalDateTime.now().minus(Duration.parse("PT2H30M"));
  4. String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt);

Groovy

  1. // import java.time.LocalDateTime
  2. // import java.time.format.DateTimeFormatter
  3. def dt = LocalDateTime.now().minusHours(2).minusMinutes(30)
  4. def s = DateTimeFormatter.ofPattern('yyyy-MM-dd HH:mm:ss').format(dt)
  1. // import java.time.*
  2. // import java.time.format.DateTimeFormatter
  3. def dt = LocalDateTime.now().minus(Duration.ofHours(2).plusMinutes(30))
  4. def s = DateTimeFormatter.ofPattern('yyyy-MM-dd HH:mm:ss').format(dt)
  1. // import java.time.*
  2. // import java.time.format.DateTimeFormatter
  3. // import java.time.temporal.ChronoUnit
  4. def dt = LocalDateTime.now().minus(Duration.of(150, ChronoUnit.MINUTES))
  5. def s = DateTimeFormatter.ofPattern('yyyy-MM-dd HH:mm:ss').format(dt)
  1. // import java.time.*
  2. // import java.time.format.DateTimeFormatter
  3. def dt = LocalDateTime.now().minus(Duration.parse('PT2H30M'))
  4. def s = DateTimeFormatter.ofPattern('yyyy-MM-dd HH:mm:ss').format(dt)

Kotlin

  1. // import java.time.LocalDateTime
  2. // import java.time.format.DateTimeFormatter
  3. val dt = LocalDateTime.now().minusHours(2).minusMinutes(30)
  4. val s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt)
  1. // import java.time.*
  2. // import java.time.format.DateTimeFormatter
  3. val dt = LocalDateTime.now() - Duration.ofHours(2).plusMinutes(30)
  4. val s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt)
  1. // import java.time.*
  2. // import java.time.format.DateTimeFormatter
  3. // import java.time.temporal.ChronoUnit
  4. val dt = LocalDateTime.now() - Duration.of(150, ChronoUnit.MINUTES)
  5. val s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt)
  1. // import java.time.*
  2. // import java.time.format.DateTimeFormatter
  3. val dt = LocalDateTime.now() - Duration.parse("PT2H30M")
  4. val s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt)

Scala

  1. // import java.time.LocalDateTime
  2. // import java.time.format.DateTimeFormatter
  3. val dt = LocalDateTime.now minusHours 2 minusMinutes 30
  4. val s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt)
  1. // import java.time._
  2. // import java.time.format.DateTimeFormatter
  3. val dt = LocalDateTime.now minus (Duration ofHours 2 plusMinutes 30)
  4. val s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt)
  1. // import java.time._
  2. // import java.time.format.DateTimeFormatter
  3. // import java.time.temporal.ChronoUnit
  4. val dt = LocalDateTime.now minus Duration.of(150, ChronoUnit.MINUTES)
  5. val s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt)
  1. // import java.time._
  2. // import java.time.format.DateTimeFormatter
  3. val dt = LocalDateTime.now minus Duration.parse("PT2H30M")
  4. val s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt)
Scala-Time を使った場合
  1. // import org.scala_tools.time.Imports._
  2. val dt = DateTime.now - 2.hours - 30.minutes
  3. val s = dt.toString("yyyy-MM-dd HH:mm:ss")

Erlang

  1. Now = erlang:localtime(),
  2. Seconds = calendar:datetime_to_gregorian_seconds(Now),
  3. D = calendar:gregorian_seconds_to_datetime(Seconds - 150 * 60),
  4. {{Year, Month, Day}, {Hour, Minute, Second}} = D,
  5. S = io:format("~4..0b-~2..0b-~2..0b ~2..0b:~2..0b:~2..0b", [Year, Month, Day, Hour, Minute, Second]).

Haskell

  1. -- import Data.Time.Clock
  2. -- import Data.Time.Format
  3. -- import Data.Time.LocalTime
  4. -- import System.Locale
  5. now <- getCurrentTime
  6. tz <- getCurrentTimeZone
  7. let d = addUTCTime (-150 * 60) now
  8. let s = formatTime defaultTimeLocale "%Y-%m-%d %H:%M:%S" $ utcToLocalTime tz d

PowerShell

  1. $d = (date).AddHours(-2.5)
  2. $s = $d.ToString('yyyy-MM-dd HH:mm:ss')
  1. $d = (date) - [TimeSpan]::FromHours(2.5)
  2. $s = $d.ToString('yyyy-MM-dd HH:mm:ss')
  1. $d = (date) - (New-Object TimeSpan 2, 30, 0)
  2. $s = $d.ToString('yyyy-MM-dd HH:mm:ss')

F#

  1. let d = System.DateTime.Now.AddHours -2.5
  2. let s = d.ToString "yyyy-MM-dd HH:mm:ss"
  1. let d = System.DateTime.Now - System.TimeSpan.FromHours 2.5
  2. let s = d.ToString "yyyy-MM-dd HH:mm:ss"
  1. let d = System.DateTime.Now - new System.TimeSpan(2, 30, 0)
  2. let s = d.ToString "yyyy-MM-dd HH:mm:ss"

C#

  1. DateTime d = DateTime.Now.AddHours(-2.5);
  2. string s = d.ToString("yyyy-MM-dd HH:mm:ss");
  1. DateTime d = DateTime.Now - TimeSpan.FromHours(2.5);
  2. string s = d.ToString("yyyy-MM-dd HH:mm:ss");
  1. DateTime d = DateTime.Now - new TimeSpan(2, 30, 0);
  2. string s = d.ToString("yyyy-MM-dd HH:mm:ss");

C++

Boost を使った場合
  1. #include <boost/date_time/posix_time/posix_time.hpp>
  2. // using namespace boost::posix_time;
  3. ptime d = second_clock::local_time() - minutes(150);
  4. string s = to_iso_extended_string(d);

Go

  1. // import "time"
  2. now := time.LocalTime()
  3. d := time.SecondsToLocalTime(now.Seconds() - 150 * 60)
  4. s := fmt.Sprintf("%04d-%02d-%02d %02d:%02d:%02d", d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second)

Rust

chrono を使った場合
  1. // use chrono::*;
  2. let dt = Local::now() - Duration::hours(2) - Duration::minutes(30);
  3. let s = dt.format("%Y-%m-%d %H:%M:%S").to_string();

Dart

  1. String f(int x) => '${x ~/ 10}${x % 10}';
  2. var d = DateTime.now().add(Duration(hours: -2, minutes: -30));
  3. var s = '${d.year}/${f(d.month)}/${f(d.day)} ${f(d.hour)}:${f(d.minute)}:${f(d.second)}';

TypeScript

  1. let f = x => '' + Math.floor(x / 10) + x % 10;
  2. let d = new Date();
  3. d.setTime(new Date() - 150 * 60 * 1000);
  4. let month = f(d.getMonth() + 1); // 月は0~11
  5. let date = f(d.getDate());
  6. let hours = f(d.getHours());
  7. let minutes = f(d.getMinutes());
  8. let seconds = f(d.getSeconds());
  9. let s = d.getFullYear() + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + seconds;
Moment.js を使った場合
  1. // import * as moment from 'moment';
  2. let s = moment().subtract(2, 'hour').subtract(30, 'minute').format('YYYY-MM-DD HH:mm:ss');
  1. // import * as moment from 'moment';
  2. let s = moment().subtract({ hour: 2, minute: 30 }).format('YYYY-MM-DD HH:mm:ss');

JavaScript

  1. let f = x => '' + Math.floor(x / 10) + x % 10;
  2. let d = new Date();
  3. d.setTime(new Date() - 150 * 60 * 1000);
  4. let month = f(d.getMonth() + 1); // 月は0~11
  5. let date = f(d.getDate());
  6. let hours = f(d.getHours());
  7. let minutes = f(d.getMinutes());
  8. let seconds = f(d.getSeconds());
  9. let s = d.getFullYear() + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + seconds;
Moment.js を使った場合
  1. // const moment = require('moment');
  2. let s = moment().subtract(2, 'hour').subtract(30, 'minute').format('YYYY-MM-DD HH:mm:ss');
  1. // const moment = require('moment');
  2. let s = moment().subtract({ hour: 2, minute: 30 }).format('YYYY-MM-DD HH:mm:ss');

CoffeeScript

  1. f = (x) -> "#{Math.floor x / 10}#{x % 10}"
  2. d = new Date
  3. d.setTime new Date - 150 * 60 * 1000 # 月は0~11
  4. s = "#{d.getFullYear()}-#{f d.getMonth() + 1}-#{f d.getDate()} #{f d.getHours()}:#{f d.getMinutes()}:#{f d.getSeconds()}"
Moment.js を使った場合
  1. # moment = require 'moment'
  2. s = moment().subtract(2, 'hour').subtract(30, 'minute').format 'YYYY-MM-DD HH:mm:ss'
  1. # moment = require 'moment'
  2. s = moment().subtract(hour: 2, minute: 30).format 'YYYY-MM-DD HH:mm:ss'

Ruby

  1. d = Time.now - 150 * 60 # 数値部分の単位は秒
  2. s = d.strftime '%Y-%m-%d %H:%M:%S'
Ruby on Rails の場合
  1. d = Time.now - 2.5.hours
  2. s = d.strftime '%Y-%m-%d %H:%M:%S'
  1. d = 2.5.hours.ago # ago は、現在時刻からの引き算をするメソッド
  2. s = d.strftime '%Y-%m-%d %H:%M:%S'

Python

  1. # from datetime import datetime
  2. # from datetime import timedelta
  3. d = datetime.now() - timedelta(hours = 2, minutes = 30)
  4. s = d.strftime('%Y-%m-%d %H:%M:%S')

PHP

  1. $d = new DateTime('-2 hours -30 minutes');
  2. $s = $d->format('Y-m-d H:i:s');

Perl

  1. # use Time::Piece;
  2. my $d = localtime() - 150 * 60; # 数値部分の単位は秒
  3. my $s = $d->date . ' ' . $d->time;
  1. # use Time::Piece;
  2. my $d = localtime() - 150 * 60; # 数値部分の単位は秒
  3. my $s = "@{[ $d->date ]} @{[ $d->time ]}";
  1. # use Time::Piece;
  2. my $d = localtime() - 150 * 60; # 数値部分の単位は秒
  3. my $s = $d->strftime('%Y-%m-%d %H:%M:%S');

文字列から日時のオブジェクトを作り、その曜日の略称(英語と日本語)を得る

日本語環境で実行するものとする。

Java

  1. // import java.time.LocalDate;
  2. // import java.time.format.DateTimeFormatter;
  3. LocalDate d = LocalDate.parse("2010-1-3", DateTimeFormatter.ofPattern("yyyy-M-d"));
  4. String en = DateTimeFormatter.ofPattern("E", Locale.US).format(d);
  5. String ja = DateTimeFormatter.ofPattern("E").format(d);
  1. // import java.time.LocalDate;
  2. // import java.time.format.*;
  3. // import java.time.temporal.TemporalQueries;
  4. LocalDate d = DateTimeFormatter.ofPattern("yyyy-M-d").parse("2010-1-3", TemporalQueries.localDate());
  5. String en = d.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.US);
  6. String ja = d.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.getDefault());

Groovy

  1. // import java.time.LocalDate
  2. // import java.time.format.*
  3. def d = LocalDate.parse('2010-1-3', DateTimeFormatter.ofPattern('yyyy-M-d'))
  4. def en = DateTimeFormatter.ofPattern('E', Locale.US).format(d)
  5. def ja = DateTimeFormatter.ofPattern('E').format(d)
  1. // import java.time.LocalDate
  2. // import java.time.format.*
  3. // import java.time.temporal.TemporalQueries
  4. def d = DateTimeFormatter.ofPattern('yyyy-M-d').parse('2010-1-3', TemporalQueries.localDate())
  5. def en = d.dayOfWeek.getDisplayName(TextStyle.SHORT, Locale.US)
  6. def ja = d.dayOfWeek.getDisplayName(TextStyle.SHORT, Locale.default)

Kotlin

  1. // import java.util.Locale
  2. // import java.time.LocalDate
  3. // import java.time.format.DateTimeFormatter
  4. val d = LocalDate.parse("2010-1-3", DateTimeFormatter.ofPattern("yyyy-M-d"))
  5. val en = DateTimeFormatter.ofPattern("E", Locale.US).format(d)
  6. val ja = DateTimeFormatter.ofPattern("E").format(d)
  1. // import java.util.Locale
  2. // import java.time.LocalDate
  3. // import java.time.format.*
  4. // import java.time.temporal.TemporalQueries
  5. val d = DateTimeFormatter.ofPattern("yyyy-M-d").parse("2010-1-3", TemporalQueries.localDate())
  6. val en = d.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.US)
  7. val ja = d.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.getDefault())

Scala

  1. // import java.util.Locale
  2. // import java.time.LocalDate
  3. // import java.time.format._
  4. val d = LocalDate.parse("2010-1-3", DateTimeFormatter.ofPattern("yyyy-M-d"))
  5. val en = DateTimeFormatter.ofPattern("E", Locale.US).format(d)
  6. val ja = DateTimeFormatter.ofPattern("E").format(d)
  1. // import java.util.Locale
  2. // import java.time.LocalDate
  3. // import java.time.format._
  4. // import java.time.temporal.TemporalQueries
  5. val d = DateTimeFormatter.ofPattern("yyyy-M-d").parse("2010-1-3", TemporalQueries.localDate)
  6. val en = d.getDayOfWeek.getDisplayName(TextStyle.SHORT, Locale.US)
  7. val ja = d.getDayOfWeek.getDisplayName(TextStyle.SHORT, Locale.getDefault)
Scala-Time を使った場合
  1. // import java.util.Locale
  2. // import org.scala_tools.time.Imports._
  3. val dt = new DateTime("2010-1-3")
  4. val en = dt.dayOfWeek.getAsShortText(Locale.US)
  5. val ja = dt.dayOfWeek.getAsShortText

Erlang

  1. {ok, [Year, Month, Day], []} = io_lib:fread("~d-~d-~d", "2010-1-3"),
  2. DayOfWeek = calendar:day_of_the_week({Year, Month, Day}), %% 1:月曜~7:日曜
  3. En = element(DayOfWeek, {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}),
  4. Ja = element(DayOfWeek, {"月", "火", "水", "木", "金", "土", "日"}).

Haskell

  1. -- import Data.Time.Clock
  2. -- import Data.Time.Format
  3. -- import Numeric
  4. -- import System.Locale
  5. let Just d = parseTime defaultTimeLocale "%Y-%m-%d" "2010-01-03" :: Maybe UTCTime
  6. let en = formatTime defaultTimeLocale "%a" d
  7. let [(dayOfWeek, "")] = readDec $ formatTime defaultTimeLocale "%u" d
  8. let ja = ["月", "火", "水", "木", "金", "土", "日"] !! (dayOfWeek - 1)

PowerShell

  1. $d = [DateTime]::ParseExact('2010-1-3', 'yyyy-M-d', $Null)
  2. $en = $d.ToString('ddd', [Globalization.CultureInfo]::GetCultureInfo('en-US'))
  3. $ja = $d.ToString('ddd')

F#

  1. // open System.Globalization
  2. let dt = System.DateTime.ParseExact("2010-1-3", "yyyy-M-d", null)
  3. let en = dt.ToString("ddd", CultureInfo.GetCultureInfo "en-US")
  4. let ja = dt.ToString "ddd"

C#

  1. // using System.Globalization;
  2. DateTime dt = DateTime.ParseExact("2010-1-3", "yyyy-M-d", null);
  3. string en = dt.ToString("ddd", CultureInfo.GetCultureInfo("en-US"));
  4. string ja = dt.ToString("ddd");

Go

  1. // import "time"
  2. t, err := time.Parse("2006-1-2", "2010-1-3") // "2006-1-2" は、書式の指定に用いる標準の日付
  3. if err != nil { return err }
  4. days := t.Seconds() / 24 / 60 / 60 // 曜日は自動で計算されないのでここで計算する
  5. t.Weekday = int((days + 4) % 7) // 4 は、1970年1月1日の曜日(木曜)を表す
  6. en := t.Format("Mon")
  7. ja := []string{"日", "月", "火", "水", "木", "金", "土"}[t.Weekday]

Rust

chrono を使った場合
  1. // use chrono::prelude::*;
  2. let s = "2010-1-3";
  3. let dt = NaiveDate::parse_from_str(&s, "%Y-%-m-%-d").unwrap();
  4. let en = dt.format("%a").to_string();
  5. let ja = dt.format_localized("%a", Locale::ja_JP).to_string();

Dart

  1. var list = '2010-1-3'.split('-').map((s) => int.parse(s)).toList();
  2. var d = DateTime(list[0], list[1], list[2]);
  3. var en = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][d.weekday - 1];
  4. var ja = '月火水木金土日'.substring(d.weekday - 1, d.weekday);

TypeScript

  1. let d = new Date('2010-1-3'.replace(/-/g, '/'));
  2. let en = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][d.getDay()];
  3. let ja = '日月火水木金土'[d.getDay()];
Moment.js を使った場合
  1. // import * as moment from 'moment';
  2. let m = moment('2010-1-3', 'YYYY-M-D');
  3. let en = m.format('ddd');
  4. let ja = m.locale('ja').format('ddd');

JavaScript

  1. let d = new Date('2010-1-3'.replace(/-/g, '/'));
  2. let en = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][d.getDay()];
  3. let ja = '日月火水木金土'[d.getDay()];
Moment.js を使った場合
  1. // const moment = require('moment');
  2. let m = moment('2010-1-3', 'YYYY-M-D');
  3. let en = m.format('ddd');
  4. let ja = m.locale('ja').format('ddd');

CoffeeScript

  1. d = new Date '2010-1-3'.replace(/-/g, '/')
  2. en = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][d.getDay()]
  3. ja = '日月火水木金土'[d.getDay()]
Moment.js を使った場合
  1. # moment = require 'moment'
  2. m = moment '2010-1-3', 'YYYY-M-D'
  3. en = m.format 'ddd'
  4. ja = m.locale('ja').format 'ddd'

Ruby

  1. # require 'date'
  2. d = Date.strptime '2010-1-3', '%Y-%m-%d'
  3. en = d.strftime '%a'
  4. ja = '日月火水木金土'[d.wday]
  1. # require 'date'
  2. d = DateTime.strptime '2010-1-3', '%Y-%m-%d'
  3. en = d.strftime '%a'
  4. ja = '日月火水木金土'[d.wday]

Python

  1. # import datetime
  2. # import locale
  3. d = datetime.datetime.strptime('2010-1-3', '%Y-%m-%d')
  4. locale.setlocale(locale.LC_ALL, 'C')
  5. en = d.strftime('%a')
  6. locale.setlocale(locale.LC_ALL, '')
  7. ja = d.strftime('%a')
  1. # import locale
  2. # import time
  3. t = time.strptime('2010-1-3', '%Y-%m-%d')
  4. locale.setlocale(locale.LC_ALL, 'C')
  5. en = time.strftime('%a', t)
  6. locale.setlocale(locale.LC_ALL, '')
  7. ja = time.strftime('%a', t)

PHP

  1. $d = DateTime::createFromFormat('Y-m-d', '2010-1-3');
  2. $en = $d->format('D');
  3. $array = ['日', '月', '火', '水', '木', '金', '土'];
  4. $ja = $array[$d->format('w')];

Perl

  1. # use Time::Piece;
  2. my $d = Time::Piece->strptime('2010-1-3', '%Y-%m-%d');
  3. my $en = $d->day;
  4. my $ja = $d->strftime('%a');

年・月・日の整数値から日時のオブジェクトを作り、現在の日付との差(日数)を求める

Java

  1. // import java.time.LocalDate;
  2. // import java.time.temporal.ChronoUnit;
  3. LocalDate d = LocalDate.of(2010, 1, 3);
  4. long days = ChronoUnit.DAYS.between(d, LocalDate.now());
  1. // import java.time.LocalDate;
  2. // import java.time.temporal.ChronoUnit;
  3. LocalDate d = LocalDate.of(2010, 1, 3);
  4. long days = d.until(LocalDate.now(), ChronoUnit.DAYS);

Groovy

  1. // import java.time.LocalDate
  2. // import java.time.temporal.ChronoUnit
  3. def d = LocalDate.of(2010, 1, 3)
  4. def days = ChronoUnit.DAYS.between(d, LocalDate.now())
  1. // import java.time.LocalDate
  2. // import java.time.temporal.ChronoUnit
  3. def d = LocalDate.of(2010, 1, 3);
  4. def days = d.until(LocalDate.now(), ChronoUnit.DAYS)

Kotlin

  1. // import java.time.LocalDate
  2. // import java.time.temporal.ChronoUnit
  3. val d = LocalDate.of(2010, 1, 3)
  4. val days = ChronoUnit.DAYS.between(d, LocalDate.now)
  1. // import java.time.LocalDate
  2. // import java.time.temporal.ChronoUnit
  3. val d = LocalDate.of(2010, 1, 3)
  4. val days = d.until(LocalDate.now, ChronoUnit.DAYS)

Scala

  1. // import java.time.LocalDate
  2. // import java.time.temporal.ChronoUnit
  3. val d = LocalDate.of(2010, 1, 3)
  4. val days = ChronoUnit.DAYS.between(d, LocalDate.now)
  1. // import java.time.LocalDate
  2. // import java.time.temporal.ChronoUnit
  3. val d = LocalDate.of(2010, 1, 3)
  4. val days = d.until(LocalDate.now, ChronoUnit.DAYS)
Scala-Time を使った場合
  1. // import org.joda.time.{DateMidnight, PeriodType}
  2. // import org.scala_tools.time.Imports._
  3. val dm = new DateMidnight(2010, 1, 3)
  4. val today = new DateMidnight
  5. val days = new Period(dm, today, PeriodType.days).days

Erlang

  1. D = {2010, 1, 3},
  2. Days = calendar:date_to_gregorian_days(date()) - calendar:date_to_gregorian_days(D).

Haskell

  1. -- import Data.Time.Calendar
  2. -- import Data.Time.Clock
  3. UTCTime today _ <- getCurrentTime
  4. let d = fromGregorian 2010 1 3
  5. let days = diffDays today d

PowerShell

  1. $d = New-Object DateTime 2010, 1, 3
  2. $days = ([DateTime]::Today - $d).Days
  1. $d = date -Year 2010 -Month 1 -Day 3
  2. $days = [Math]::Round(((date) - $d).TotalDays)

F#

  1. let d = new System.DateTime(2010, 1, 3)
  2. let days = (System.DateTime.Today - d).Days

C#

  1. DateTime d = new DateTime(2010, 1, 3);
  2. int days = (DateTime.Today - d).Days;

C++

Boost を使った場合
  1. #include <boost/date_time/gregorian/gregorian.hpp>
  2. // using namespace boost::gregorian;
  3. date d(2010, 1, 3);
  4. int days = (day_clock::local_day() - d).days();

Go

  1. // import "time"
  2. now := time.LocalTime() // now は構造体へのポインタ
  3. d := *now // ポインタが指す先の構造体をコピーする
  4. d.Year, d.Month, d.Day = 2010, 1, 3
  5. days := (d.Seconds() - now.Seconds()) / 24 / 60 / 60

Rust

chrono を使った場合
  1. // use chrono::prelude::*;
  2. let d = Local.with_ymd_and_hms(2010, 1, 3, 0, 0, 0).unwrap().date_naive();
  3. let days = (Local::now().date_naive() - d).num_days();

Dart

  1. var now = DateTime.now();
  2. var d = DateTime(2010, 1, 3, now.hour, now.minute, now.second, now.millisecond);
  3. var days = now.difference(d).inDays;

TypeScript

  1. let now = new Date();
  2. let d = new Date(2010, 0, 3, now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds());
  3. let days = (now.getTime() - d.getTime()) / 24 / 60 / 60 / 1000;
Moment.js を使った場合
  1. // import * as moment from 'moment';
  2. let m = moment([2010, 0, 3]);
  3. let days = moment().diff(m, 'day');
  1. // import * as moment from 'moment';
  2. let m = moment({ year: 2010, month: 0, day: 3 });
  3. let days = moment().diff(m, 'day');

JavaScript

  1. let now = new Date();
  2. let d = new Date(2010, 0, 3, now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds());
  3. let days = (now.getTime() - d.getTime()) / 24 / 60 / 60 / 1000;
Moment.js を使った場合
  1. // const moment = require('moment');
  2. let m = moment([2010, 0, 3]);
  3. let days = moment().diff(m, 'day');
  1. // const moment = require('moment');
  2. let m = moment({ year: 2010, month: 0, day: 3 });
  3. let days = moment().diff(m, 'day');

CoffeeScript

  1. now = new Date
  2. d = new Date 2010, 0, 3, now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds()
  3. days = (now.getTime() - d.getTime()) / 24 / 60 / 60 / 1000
Moment.js を使った場合
  1. # moment = require 'moment'
  2. m = moment [2010, 0, 3]
  3. days = moment().diff m, 'day'
  1. # moment = require 'moment'
  2. m = moment year: 2010, month: 0, day: 3
  3. days = moment().diff m, 'day'

Ruby

  1. d = Time.local 2010, 1, 3
  2. days = ((Time.today - d) / 24 / 60 / 60).to_i
Ruby on Rails の場合
  1. d = Time.local 2010, 1, 3
  2. days = ((Time.today - d) / 1.day).to_i

Python

  1. # from datetime import date
  2. d = date(2010, 1, 3)
  3. days = (date.today() - d).days

PHP

  1. $d = new DateTime();
  2. $d->setDate(2010, 1, 3);
  3. $d->setTime(0, 0);
  4. $today = new DateTime('today');
  5. $days = intval($today->diff($d)->format('%r%a'));

Perl

  1. # use Time::Local;
  2. # use Time::localtime;
  3. # use Time::Piece;
  4. my $now = time;
  5. my $nowObj = localtime $now; # $nowObj が指すオブジェクトの型は Time::Piece
  6. my $t = timelocal $nowObj->sec, $nowObj->min, $nowObj->hour, 3, 0, 2010; # 月は0~11
  7. my $days = ($now - $t) / 24 / 60 / 60;
CPAN の Date::Simple を使った場合
  1. # use Date::Simple;
  2. my $today = Date::Simple::today;
  3. my $d = Date::Simple::ymd 2010, 1, 3;
  4. my $days = $today - $d;

年・月・日・時・分・秒の整数値から日時のオブジェクトを作り、それが過去の日時かどうか判定する

Java

  1. // import java.time.LocalDateTime;
  2. LocalDateTime dt = LocalDateTime.of(2010, 1, 3, 12, 34, 56);
  3. boolean isPast = dt.isBefore(LocalDateTime.now());

Groovy

  1. // import java.time.LocalDateTime
  2. def dt = LocalDateTime.of(2010, 1, 3, 12, 34, 56)
  3. def isPast = dt.isBefore(LocalDateTime.now())

Kotlin

  1. // import java.time.LocalDateTime
  2. val dt = LocalDateTime.of(2010, 1, 3, 12, 34, 56)
  3. val isPast = dt.isBefore(LocalDateTime.now)

Scala

  1. // import java.time.LocalDateTime
  2. val dt = LocalDateTime.of(2010, 1, 3, 12, 34, 56)
  3. val isPast = dt.isBefore(LocalDateTime.now)
Scala-Time を使った場合
  1. // import org.joda.time.DateMidnight
  2. // import org.scala_tools.time.Imports._
  3. val dt = new DateMidnight(2010, 1, 3).toDateTime + 12.hours + 34.minutes + 56.seconds
  4. val isPast = dt.isBeforeNow
  1. // import org.joda.time.DateMidnight
  2. // import org.scala_tools.time.Imports._
  3. val dt = new DateMidnight(2010, 1, 3).toDateTime + 12.hours + 34.minutes + 56.seconds
  4. val isPast = dt < DateTime.now

Erlang

  1. Now = erlang:localtime(),
  2. T = {{2010, 1, 3}, {12, 34, 56}},
  3. IsPast = T < Now.

Haskell

  1. -- import Data.Time.Calendar
  2. -- import Data.Time.Clock
  3. -- import Data.Time.LocalTime
  4. tz <- getCurrentTimeZone
  5. now <- getCurrentTime
  6. let d = LocalTime (fromGregorian 2010 1 3) (TimeOfDay 12 34 56)
  7. let isPast = d < utcToLocalTime tz now
  1. -- import Data.Time.Calendar
  2. -- import Data.Time.Clock
  3. -- import Data.Time.LocalTime
  4. tz <- getCurrentTimeZone
  5. now <- getCurrentTime
  6. let d = localTimeToUTC tz $ LocalTime (fromGregorian 2010 1 3) (TimeOfDay 12 34 56)
  7. let isPast = d < now

PowerShell

  1. $d = New-Object DateTime 2010, 1, 3, 12, 34, 56
  2. $isPast = $d -lt (date)
  1. $d = date -Year 2010 -Month 1 -Day 3 -Hour 12 -Minute 34 -Second 56
  2. $isPast = $d -lt (date)

F#

  1. let d = new System.DateTime(2010, 1, 3, 12, 34, 56)
  2. let isPast = d < System.DateTime.Now

C#

  1. DateTime d = new DateTime(2010, 1, 3, 12, 34, 56);
  2. bool isPast = d < DateTime.now;

C++

Boost を使った場合
  1. #include <boost/date_time/posix_time/posix_time.hpp>
  2. #include <boost/date_time/gregorian/gregorian.hpp>
  3. // using namespace boost::posix_time;
  4. ptime d(boost::gregorian::date(2010, 1, 3), time_duration(12, 34, 56));
  5. bool is_past = d < second_clock::local_time();

Go

  1. // import "time"
  2. now := time.LocalTime() // now は構造体へのポインタ
  3. d := *now // ポインタが指す先の構造体をコピーする
  4. d.Year, d.Month, d.Day = 2010, 1, 3
  5. d.Hour, d.Minute, d.Second = 12, 34, 56
  6. isPast := d.Seconds() < now.Seconds()

Rust

chrono を使った場合
  1. // use chrono::prelude::*;
  2. let d = Local.with_ymd_and_hms(2010, 1, 3, 12, 34, 56).unwrap();
  3. let is_past = d < Local::now();

Dart

  1. var now = DateTime.now();
  2. var d = DateTime(2010, 1, 3, 12, 34, 56);
  3. var isPast = d.isBefore(now);

TypeScript

  1. let now = new Date();
  2. let d = new Date(2010, 0, 3, 12, 34, 56); // 月は0~11
  3. let isPast = d.getTime() < now.getTime();
Moment.js を使った場合
  1. // import * as moment from 'moment';
  2. let m = moment([2010, 0, 3, 12, 34, 56]); // 月は0~11
  3. let isPast = m.isBefore(moment());

JavaScript

  1. let now = new Date();
  2. let d = new Date(2010, 0, 3, 12, 34, 56); // 月は0~11
  3. let isPast = d.getTime() < now.getTime();
Moment.js を使った場合
  1. // const moment = require('moment');
  2. let m = moment([2010, 0, 3, 12, 34, 56]); // 月は0~11
  3. let isPast = m.isBefore(moment());

CoffeeScript

  1. now = new Date
  2. d = new Date 2010, 0, 3, 12, 34, 56 # 月は0~11
  3. isPast = d.getTime() < now.getTime()
Moment.js を使った場合
  1. # moment = require 'moment'
  2. m = moment [2010, 0, 3, 12, 34, 56] # 月は0~11
  3. isPast = m.isBefore moment()

Ruby

  1. d = Time.local 2010, 1, 3, 12, 34, 56
  2. is_past = d < Time.now

Python

  1. # from datetime import datetime
  2. d = datetime(2010, 1, 3, 12, 34, 56)
  3. is_past = d < datetime.now()

PHP

  1. $d = new DateTime();
  2. $d->setDate(2010, 1, 3);
  3. $d->setTime(12, 34, 56);
  4. $isPast = $d->diff(new DateTime())->format('%R') === '+';

Perl

  1. # use Time::Local;
  2. # use Time::Piece;
  3. my $t = timelocal 56, 34, 12, 3, 0, 2010; # 秒、分、時、日、月(0~11)、年
  4. my $isPast = $t < time;

戻る

目次

指定された値の2乗を返す関数 Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
誤差のない四則演算 Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
代金の割引計算 Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
現在の2時間半前の時刻を文字列で表す Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
文字列から日時のオブジェクトを作り、その曜日の略称(英語と日本語)を得る Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
年・月・日の整数値から日時のオブジェクトを作り、現在の日付との差(日数)を求める Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl
年・月・日・時・分・秒の整数値から日時のオブジェクトを作り、それが過去の日時かどうか判定する Java Groovy Kotlin Scala Erlang Haskell PowerShell F# C# C++ Go Rust Dart TypeScript JavaScript CoffeeScript Ruby Python PHP Perl