数値
Java
- public static int square(int x) {
- return x * x;
- }
Kotlin
- fun square(x: Int) = x * x
- fun square(x: Int): Int { return x * x }
Scala
- def square(x: Int) = x * x
- def square(x: Int): Int = { x * x }
PowerShell
- function square($x) {
- $x * $x
- }
- function square {
- param($x)
- $x * $x
- }
- function square {
- $args[0] * $args[0]
- }
F#
- let square (x : int64) = pown x 2
C#
C# 6.0以降
- public static int Square(int x) => x * x;
C++
- #include <math.h>
- double square(const double x) {
- return pow(x, 2);
- }
Go
- func square(x float64) float64 {
- return math.Pow(x, 2)
- }
Rust
- pub fn square(n: i32) -> i32 {
- n * n
- }
Dart
- num square(num x) => pow(x, 2);
- num square(num x) {
- return pow(x, 2);
- }
TypeScript
- function square(x) {
- return Math.pow(x, 2);
- }
JavaScript
- function square(x) {
- return Math.pow(x, 2);
- }
CoffeeScript
- square = (x) -> Math.pow x, 2
Python
- def square(x):
- return x ** 2
- def square(x):
- return pow(x, 2)
PHP
- function square($x) {
- return $x ** 2;
- }
Perl
- sub square {
- my $x = shift;
- $x ** 2;
- }
- sub square {
- shift() ** 2;
- }
0.1×3-0.3=0.0 だが、2進数で計算すると誤差が出て 5.551115123125783e-17 になってしまう。
ここでは、その誤差を避ける計算方法を挙げる。
Java
- BigDecimal result = new BigDecimal("0.1").multiply(new BigDecimal(3)).subtract(new BigDecimal("0.3"));
- double d = result.doubleValue();
Groovy
- def result = 0.1 * 3 - 0.3
- double d = result
Kotlin
- val result = BigDecimal("0.1") * 3.toBigDecimal() - BigDecimal("0.3")
- val d = result.toDouble()
Scala
- val result = BigDecimal("0.1") * 3 - BigDecimal("0.3")
- val d = result.doubleValue
Haskell
分数を表す型を使う
- let result = (1 % 10) * 3 - (3 % 10)
- let d = fromRational result
PowerShell
- $result = [decimal] 0.1 * 3 - [decimal] 0.3
- $d = [double] $result
F#
- let result = 0.1M * 3M - 0.3M
- let f = float result
F# PowerPack を使った場合
分数を表す型を使う
- let result = (1N / 10N) * 3N - (3N / 10N)
- let f = float result
C#
- decimal result = 0.1M * 3 - 0.3M;
- double d = (double)result;
C++
Boost を使った場合
分数を表す型を使う
- #include <boost/rational.hpp>
- boost::rational<int> result = boost::rational<int>(1, 10) * 3 - boost::rational<int>(3, 10);
- double d = boost::rational_cast<double>(result);
Go
分数を表す型を使う
- mul := big.NewRat(0, 0).Mul(big.NewRat(1, 10), big.NewRat(3, 1))
- result := big.NewRat(0, 0).Sub(mul, big.NewRat(3, 10))
- f := float(result.Num().Int64()) / float(result.Denom().Int64())
Ruby
- result = BigDecimal('0.1') * 3 - BigDecimal('0.3')
- f = result.to_f
Python
- result = Decimal('0.1') * 3 - Decimal('0.3')
- f = float(result)
PHP
- bcscale(1);
- $result = bcsub(bcmul('0.1', '3'), '0.3');
- $f = (float)$result;
Perl
- my $result = Math::BigFloat->new('0.1') * 3 - Math::BigFloat->new('0.3');
Java
- BigDecimal unitPrice = new BigDecimal(480);
- int buyCount = 3;
- BigDecimal discountRate = new BigDecimal("0.06");
- long postageExemptionCondition = 1500;
- BigDecimal postage = new BigDecimal(300);
- BigDecimal sum = unitPrice.multiply(new BigDecimal(buyCount));
- sum = sum.multiply(BigDecimal.ONE.subtract(discountRate));
- sum = sum.setScale(0, RoundingMode.DOWN);
- if (sum.compareTo(new BigDecimal(postageExemptionCondition)) < 0) {
- sum = sum.add(postage);
- }
Groovy
- def unitPrice = 480
- def buyCount = 3
- def discountRate = 0.06
- def postageExemptionCondition = 1500
- def postage = 300
- def sum = unitPrice * buyCount * (1 - discountRate)
- sum = sum.setScale(0, RoundingMode.DOWN)
- if (sum < postageExemptionCondition) {
- sum += postage
- }
Kotlin
- val unitPrice = 480
- val buyCount = 3
- val discountRate = BigDecimal("0.06")
- val postageExemptionCondition = 1500
- val postage = 300
- var sum = BigDecimal(unitPrice * buyCount)
- sum *= BigDecimal(1) - discountRate
- sum = sum.setScale(0, RoundingMode.DOWN)
- if (sum < postageExemptionCondition.toBigDecimal()) {
- sum += postage.toBigDecimal()
- }
Scala
- val unitPrice = 480
- val buyCount = 3
- val discountRate = BigDecimal("0.06")
- val postageExemptionCondition = 1500
- val postage = 300
- var sum = BigDecimal(unitPrice * buyCount)
- sum *= BigDecimal(1) - discountRate
- sum = sum.setScale(0, BigDecimal.RoundingMode.ROUND_DOWN)
- if (sum < postageExemptionCondition) {
- sum += postage
- }
Haskell
- let unitPrice = 480
- let buyCount = 3
- let discountRate = 6 % 100
- let postageExemptionCondition = 1500
- let postage = 300
- let sum = truncate $ fromRational $ unitPrice * buyCount * (1 - discountRate)
- let sum' = sum + (if sum < postageExemptionCondition then postage else 0)
State モナドを使う
- trunc = (% 1) . truncate . fromRational
- modifyIf f g = get >>= \ state -> if f state then put (g state) else return ()
- let unitPrice = 480
- let buyCount = 3
- let discountRatio = 6 % 100
- let postageExemptionCondition = 1500
- let postage = 300
- let (_, sum) = runState (do
- put unitPrice
- modify (* buyCount)
- modify (* (1 - discountRatio))
- modify trunc
- modifyIf (< postageExemptionCondition) (+ postage)
- ) 0
- let sum' = numerator sum
PowerShell
- $unitPrice = 480
- $buyCount = 3
- $discountRate = [decimal] 0.06
- $postageExemptionCondition = 1500
- $postage = 300
- $sum = $unitPrice * $buyCount * (1 - $discountRate)
- $sum = [Math]::Truncate($sum)
- if ($sum -lt $postageExemptionCondition) {
- $sum += $postage
- }
F#
- let unitPrice = 480M
- let buyCount = 3M
- let discountRate = 0.06M
- let postageExemptionCondition = 1500M
- let postage = 300M
- let mutable sum = unitPrice * buyCount * (1M - discountRate)
- sum <- System.Math.Truncate sum
- if sum < postageExemptionCondition then
- sum <- sum + postage
C#
- int unitPrice = 480;
- int buyCount = 3;
- decimal discountRate = 0.06M;
- int postageExemptionCondition = 1500;
- int postage = 300;
- decimal sum = unitPrice * buyCount * (1 - discountRate);
- sum = Math.Truncate(sum);
- if (sum < postageExemptionCondition) {
- sum += postage;
- }
Go
- unitPrice := 480
- buyCount := 3
- discountRate := big.NewRat(6, 100)
- postageExemptionCondition := 1500
- postage := 300
- sumRat := big.NewRat(int64(unitPrice * buyCount), 1)
- rateRat := big.NewRat(0, 0).Sub(big.NewRat(1, 1), discountRate)
- sumRat = big.NewRat(0, 0).Mul(sumRat, rateRat)
- sum := int(sumRat.Num().Int64() / sumRat.Denom().Int64())
- if sum < postageExemptionCondition {
- sum += postage
- }
Ruby
- unit_price = 480
- buy_count = 3
- discount_rate = BigDecimal('0.06')
- postage_exemption_condition = 1500
- postage = 300
- sum = unit_price * buy_count * (1 - discount_rate)
- sum = sum.floor.to_i
- sum += postage if sum < postage_exemption_condition
Python
- unit_price = 480
- buy_count = 3
- discount_rate = Decimal('0.06')
- postage_exemption_condition = 1500
- postage = 300
- sum = unit_price * buy_count * (1 - discount_rate)
- sum = sum.to_integral_value(ROUND_DOWN)
- if sum < postage_exemption_condition:
- sum += postage
PHP
- bcscale(2);
- $unit_price = 480;
- $buy_count = 3;
- $discount_rate = '0.06';
- $postage_exemption_condition = 1500;
- $postage = 300;
- $sum = $unit_price * $buy_count;
- $sum = (int)bcmul((string)$sum, bcsub('1', $discount_rate));
- if ($sum < $postage_exemption_condition) {
- $sum += $postage;
- }
Perl
- my $unit_price = 480;
- my $buy_count = 3;
- my $discount_rate = Math::BigFloat->new('0.06');
- my $postage_exemption_condition = 1500;
- my $postage = 300;
- my $sum = Math::BigFloat->new($unit_price * $buy_count);
- $sum *= 1 - $discount_rate;
- $sum->ffround(0);
- $sum += $postage if $sum < $postage_exemption_condition;
日時
Java
- LocalDateTime dt = LocalDateTime.now().minusHours(2).minusMinutes(30);
- String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt);
- LocalDateTime dt = LocalDateTime.now().minus(Duration.ofHours(2).plusMinutes(30));
- String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt);
- LocalDateTime dt = LocalDateTime.now().minus(Duration.of(150, ChronoUnit.MINUTES));
- String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt);
- LocalDateTime dt = LocalDateTime.now().minus(Duration.parse("PT2H30M"));
- String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt);
Groovy
- def dt = LocalDateTime.now().minusHours(2).minusMinutes(30)
- def s = DateTimeFormatter.ofPattern('yyyy-MM-dd HH:mm:ss').format(dt)
- def dt = LocalDateTime.now().minus(Duration.ofHours(2).plusMinutes(30))
- def s = DateTimeFormatter.ofPattern('yyyy-MM-dd HH:mm:ss').format(dt)
- def dt = LocalDateTime.now().minus(Duration.of(150, ChronoUnit.MINUTES))
- def s = DateTimeFormatter.ofPattern('yyyy-MM-dd HH:mm:ss').format(dt)
- def dt = LocalDateTime.now().minus(Duration.parse('PT2H30M'))
- def s = DateTimeFormatter.ofPattern('yyyy-MM-dd HH:mm:ss').format(dt)
Kotlin
- val dt = LocalDateTime.now().minusHours(2).minusMinutes(30)
- val s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt)
- val dt = LocalDateTime.now() - Duration.ofHours(2).plusMinutes(30)
- val s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt)
- val dt = LocalDateTime.now() - Duration.of(150, ChronoUnit.MINUTES)
- val s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt)
- val dt = LocalDateTime.now() - Duration.parse("PT2H30M")
- val s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt)
Scala
- val dt = LocalDateTime.now minusHours 2 minusMinutes 30
- val s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt)
- val dt = LocalDateTime.now minus (Duration ofHours 2 plusMinutes 30)
- val s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt)
- val dt = LocalDateTime.now minus Duration.of(150, ChronoUnit.MINUTES)
- val s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt)
- val dt = LocalDateTime.now minus Duration.parse("PT2H30M")
- val s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(dt)
Scala-Time を使った場合
- val dt = DateTime.now - 2.hours - 30.minutes
- val s = dt.toString("yyyy-MM-dd HH:mm:ss")
Erlang
- Now = erlang:localtime(),
- Seconds = calendar:datetime_to_gregorian_seconds(Now),
- D = calendar:gregorian_seconds_to_datetime(Seconds - 150 * 60),
- {{Year, Month, Day}, {Hour, Minute, Second}} = D,
- S = io:format("~4..0b-~2..0b-~2..0b ~2..0b:~2..0b:~2..0b", [Year, Month, Day, Hour, Minute, Second]).
Haskell
- now <- getCurrentTime
- tz <- getCurrentTimeZone
- let d = addUTCTime (-150 * 60) now
- let s = formatTime defaultTimeLocale "%Y-%m-%d %H:%M:%S" $ utcToLocalTime tz d
PowerShell
- $d = (date).AddHours(-2.5)
- $s = $d.ToString('yyyy-MM-dd HH:mm:ss')
- $d = (date) - [TimeSpan]::FromHours(2.5)
- $s = $d.ToString('yyyy-MM-dd HH:mm:ss')
- $d = (date) - (New-Object TimeSpan 2, 30, 0)
- $s = $d.ToString('yyyy-MM-dd HH:mm:ss')
F#
- let d = System.DateTime.Now.AddHours -2.5
- let s = d.ToString "yyyy-MM-dd HH:mm:ss"
- let d = System.DateTime.Now - System.TimeSpan.FromHours 2.5
- let s = d.ToString "yyyy-MM-dd HH:mm:ss"
- let d = System.DateTime.Now - new System.TimeSpan(2, 30, 0)
- let s = d.ToString "yyyy-MM-dd HH:mm:ss"
C#
- DateTime d = DateTime.Now.AddHours(-2.5);
- string s = d.ToString("yyyy-MM-dd HH:mm:ss");
- DateTime d = DateTime.Now - TimeSpan.FromHours(2.5);
- string s = d.ToString("yyyy-MM-dd HH:mm:ss");
- DateTime d = DateTime.Now - new TimeSpan(2, 30, 0);
- string s = d.ToString("yyyy-MM-dd HH:mm:ss");
C++
Boost を使った場合
- #include <boost/date_time/posix_time/posix_time.hpp>
- ptime d = second_clock::local_time() - minutes(150);
- string s = to_iso_extended_string(d);
Go
- now := time.LocalTime()
- d := time.SecondsToLocalTime(now.Seconds() - 150 * 60)
- s := fmt.Sprintf("%04d-%02d-%02d %02d:%02d:%02d", d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second)
Rust
chrono を使った場合
- let dt = Local::now() - Duration::hours(2) - Duration::minutes(30);
- let s = dt.format("%Y-%m-%d %H:%M:%S").to_string();
Dart
- String f(int x) => '${x ~/ 10}${x % 10}';
- var d = DateTime.now().add(Duration(hours: -2, minutes: -30));
- var s = '${d.year}/${f(d.month)}/${f(d.day)} ${f(d.hour)}:${f(d.minute)}:${f(d.second)}';
TypeScript
- let f = x => '' + Math.floor(x / 10) + x % 10;
- let d = new Date();
- d.setTime(new Date() - 150 * 60 * 1000);
- let month = f(d.getMonth() + 1);
- let date = f(d.getDate());
- let hours = f(d.getHours());
- let minutes = f(d.getMinutes());
- let seconds = f(d.getSeconds());
- let s = d.getFullYear() + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + seconds;
Moment.js を使った場合
- let s = moment().subtract(2, 'hour').subtract(30, 'minute').format('YYYY-MM-DD HH:mm:ss');
- let s = moment().subtract({ hour: 2, minute: 30 }).format('YYYY-MM-DD HH:mm:ss');
JavaScript
- let f = x => '' + Math.floor(x / 10) + x % 10;
- let d = new Date();
- d.setTime(new Date() - 150 * 60 * 1000);
- let month = f(d.getMonth() + 1);
- let date = f(d.getDate());
- let hours = f(d.getHours());
- let minutes = f(d.getMinutes());
- let seconds = f(d.getSeconds());
- let s = d.getFullYear() + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + seconds;
Moment.js を使った場合
- let s = moment().subtract(2, 'hour').subtract(30, 'minute').format('YYYY-MM-DD HH:mm:ss');
- let s = moment().subtract({ hour: 2, minute: 30 }).format('YYYY-MM-DD HH:mm:ss');
CoffeeScript
- f = (x) -> "#{Math.floor x / 10}#{x % 10}"
- d = new Date
- d.setTime new Date - 150 * 60 * 1000
- s = "#{d.getFullYear()}-#{f d.getMonth() + 1}-#{f d.getDate()} #{f d.getHours()}:#{f d.getMinutes()}:#{f d.getSeconds()}"
Moment.js を使った場合
- s = moment().subtract(2, 'hour').subtract(30, 'minute').format 'YYYY-MM-DD HH:mm:ss'
- s = moment().subtract(hour: 2, minute: 30).format 'YYYY-MM-DD HH:mm:ss'
Ruby
- d = Time.now - 150 * 60
- s = d.strftime '%Y-%m-%d %H:%M:%S'
Ruby on Rails の場合
- d = Time.now - 2.5.hours
- s = d.strftime '%Y-%m-%d %H:%M:%S'
- d = 2.5.hours.ago
- s = d.strftime '%Y-%m-%d %H:%M:%S'
Python
- d = datetime.now() - timedelta(hours = 2, minutes = 30)
- s = d.strftime('%Y-%m-%d %H:%M:%S')
PHP
- $d = new DateTime('-2 hours -30 minutes');
- $s = $d->format('Y-m-d H:i:s');
Perl
- my $d = localtime() - 150 * 60;
- my $s = $d->date . ' ' . $d->time;
- my $d = localtime() - 150 * 60;
- my $s = "@{[ $d->date ]} @{[ $d->time ]}";
- my $d = localtime() - 150 * 60;
- my $s = $d->strftime('%Y-%m-%d %H:%M:%S');
日本語環境で実行するものとする。
Java
- LocalDate d = LocalDate.parse("2010-1-3", DateTimeFormatter.ofPattern("yyyy-M-d"));
- String en = DateTimeFormatter.ofPattern("E", Locale.US).format(d);
- String ja = DateTimeFormatter.ofPattern("E").format(d);
- LocalDate d = DateTimeFormatter.ofPattern("yyyy-M-d").parse("2010-1-3", TemporalQueries.localDate());
- String en = d.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.US);
- String ja = d.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.getDefault());
Groovy
- def d = LocalDate.parse('2010-1-3', DateTimeFormatter.ofPattern('yyyy-M-d'))
- def en = DateTimeFormatter.ofPattern('E', Locale.US).format(d)
- def ja = DateTimeFormatter.ofPattern('E').format(d)
- def d = DateTimeFormatter.ofPattern('yyyy-M-d').parse('2010-1-3', TemporalQueries.localDate())
- def en = d.dayOfWeek.getDisplayName(TextStyle.SHORT, Locale.US)
- def ja = d.dayOfWeek.getDisplayName(TextStyle.SHORT, Locale.default)
Kotlin
- val d = LocalDate.parse("2010-1-3", DateTimeFormatter.ofPattern("yyyy-M-d"))
- val en = DateTimeFormatter.ofPattern("E", Locale.US).format(d)
- val ja = DateTimeFormatter.ofPattern("E").format(d)
- val d = DateTimeFormatter.ofPattern("yyyy-M-d").parse("2010-1-3", TemporalQueries.localDate())
- val en = d.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.US)
- val ja = d.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.getDefault())
Scala
- val d = LocalDate.parse("2010-1-3", DateTimeFormatter.ofPattern("yyyy-M-d"))
- val en = DateTimeFormatter.ofPattern("E", Locale.US).format(d)
- val ja = DateTimeFormatter.ofPattern("E").format(d)
- val d = DateTimeFormatter.ofPattern("yyyy-M-d").parse("2010-1-3", TemporalQueries.localDate)
- val en = d.getDayOfWeek.getDisplayName(TextStyle.SHORT, Locale.US)
- val ja = d.getDayOfWeek.getDisplayName(TextStyle.SHORT, Locale.getDefault)
Scala-Time を使った場合
- val dt = new DateTime("2010-1-3")
- val en = dt.dayOfWeek.getAsShortText(Locale.US)
- val ja = dt.dayOfWeek.getAsShortText
Erlang
- {ok, [Year, Month, Day], []} = io_lib:fread("~d-~d-~d", "2010-1-3"),
- DayOfWeek = calendar:day_of_the_week({Year, Month, Day}),
- En = element(DayOfWeek, {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}),
- Ja = element(DayOfWeek, {"月", "火", "水", "木", "金", "土", "日"}).
Haskell
- let Just d = parseTime defaultTimeLocale "%Y-%m-%d" "2010-01-03" :: Maybe UTCTime
- let en = formatTime defaultTimeLocale "%a" d
- let [(dayOfWeek, "")] = readDec $ formatTime defaultTimeLocale "%u" d
- let ja = ["月", "火", "水", "木", "金", "土", "日"] !! (dayOfWeek - 1)
PowerShell
- $d = [DateTime]::ParseExact('2010-1-3', 'yyyy-M-d', $Null)
- $en = $d.ToString('ddd', [Globalization.CultureInfo]::GetCultureInfo('en-US'))
- $ja = $d.ToString('ddd')
F#
- let dt = System.DateTime.ParseExact("2010-1-3", "yyyy-M-d", null)
- let en = dt.ToString("ddd", CultureInfo.GetCultureInfo "en-US")
- let ja = dt.ToString "ddd"
C#
- DateTime dt = DateTime.ParseExact("2010-1-3", "yyyy-M-d", null);
- string en = dt.ToString("ddd", CultureInfo.GetCultureInfo("en-US"));
- string ja = dt.ToString("ddd");
Go
- t, err := time.Parse("2006-1-2", "2010-1-3")
- if err != nil { return err }
- days := t.Seconds() / 24 / 60 / 60
- t.Weekday = int((days + 4) % 7)
- en := t.Format("Mon")
- ja := []string{"日", "月", "火", "水", "木", "金", "土"}[t.Weekday]
Rust
chrono を使った場合
- let s = "2010-1-3";
- let dt = NaiveDate::parse_from_str(&s, "%Y-%-m-%-d").unwrap();
- let en = dt.format("%a").to_string();
- let ja = dt.format_localized("%a", Locale::ja_JP).to_string();
Dart
- var list = '2010-1-3'.split('-').map((s) => int.parse(s)).toList();
- var d = DateTime(list[0], list[1], list[2]);
- var en = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][d.weekday - 1];
- var ja = '月火水木金土日'.substring(d.weekday - 1, d.weekday);
TypeScript
- let d = new Date('2010-1-3'.replace(/-/g, '/'));
- let en = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][d.getDay()];
- let ja = '日月火水木金土'[d.getDay()];
Moment.js を使った場合
- let m = moment('2010-1-3', 'YYYY-M-D');
- let en = m.format('ddd');
- let ja = m.locale('ja').format('ddd');
JavaScript
- let d = new Date('2010-1-3'.replace(/-/g, '/'));
- let en = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][d.getDay()];
- let ja = '日月火水木金土'[d.getDay()];
Moment.js を使った場合
- let m = moment('2010-1-3', 'YYYY-M-D');
- let en = m.format('ddd');
- let ja = m.locale('ja').format('ddd');
CoffeeScript
- d = new Date '2010-1-3'.replace(/-/g, '/')
- en = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][d.getDay()]
- ja = '日月火水木金土'[d.getDay()]
Moment.js を使った場合
- m = moment '2010-1-3', 'YYYY-M-D'
- en = m.format 'ddd'
- ja = m.locale('ja').format 'ddd'
Ruby
- d = Date.strptime '2010-1-3', '%Y-%m-%d'
- en = d.strftime '%a'
- ja = '日月火水木金土'[d.wday]
- d = DateTime.strptime '2010-1-3', '%Y-%m-%d'
- en = d.strftime '%a'
- ja = '日月火水木金土'[d.wday]
Python
- d = datetime.datetime.strptime('2010-1-3', '%Y-%m-%d')
- locale.setlocale(locale.LC_ALL, 'C')
- en = d.strftime('%a')
- locale.setlocale(locale.LC_ALL, '')
- ja = d.strftime('%a')
- t = time.strptime('2010-1-3', '%Y-%m-%d')
- locale.setlocale(locale.LC_ALL, 'C')
- en = time.strftime('%a', t)
- locale.setlocale(locale.LC_ALL, '')
- ja = time.strftime('%a', t)
PHP
- $d = DateTime::createFromFormat('Y-m-d', '2010-1-3');
- $en = $d->format('D');
- $array = ['日', '月', '火', '水', '木', '金', '土'];
- $ja = $array[$d->format('w')];
Perl
- my $d = Time::Piece->strptime('2010-1-3', '%Y-%m-%d');
- my $en = $d->day;
- my $ja = $d->strftime('%a');
Java
- LocalDate d = LocalDate.of(2010, 1, 3);
- long days = ChronoUnit.DAYS.between(d, LocalDate.now());
- LocalDate d = LocalDate.of(2010, 1, 3);
- long days = d.until(LocalDate.now(), ChronoUnit.DAYS);
Groovy
- def d = LocalDate.of(2010, 1, 3)
- def days = ChronoUnit.DAYS.between(d, LocalDate.now())
- def d = LocalDate.of(2010, 1, 3);
- def days = d.until(LocalDate.now(), ChronoUnit.DAYS)
Kotlin
- val d = LocalDate.of(2010, 1, 3)
- val days = ChronoUnit.DAYS.between(d, LocalDate.now)
- val d = LocalDate.of(2010, 1, 3)
- val days = d.until(LocalDate.now, ChronoUnit.DAYS)
Scala
- val d = LocalDate.of(2010, 1, 3)
- val days = ChronoUnit.DAYS.between(d, LocalDate.now)
- val d = LocalDate.of(2010, 1, 3)
- val days = d.until(LocalDate.now, ChronoUnit.DAYS)
Scala-Time を使った場合
- val dm = new DateMidnight(2010, 1, 3)
- val today = new DateMidnight
- val days = new Period(dm, today, PeriodType.days).days
Erlang
- D = {2010, 1, 3},
- Days = calendar:date_to_gregorian_days(date()) - calendar:date_to_gregorian_days(D).
Haskell
- UTCTime today _ <- getCurrentTime
- let d = fromGregorian 2010 1 3
- let days = diffDays today d
PowerShell
- $d = New-Object DateTime 2010, 1, 3
- $days = ([DateTime]::Today - $d).Days
- $d = date -Year 2010 -Month 1 -Day 3
- $days = [Math]::Round(((date) - $d).TotalDays)
F#
- let d = new System.DateTime(2010, 1, 3)
- let days = (System.DateTime.Today - d).Days
C#
- DateTime d = new DateTime(2010, 1, 3);
- int days = (DateTime.Today - d).Days;
C++
Boost を使った場合
- #include <boost/date_time/gregorian/gregorian.hpp>
- date d(2010, 1, 3);
- int days = (day_clock::local_day() - d).days();
Go
- now := time.LocalTime()
- d := *now
- d.Year, d.Month, d.Day = 2010, 1, 3
- days := (d.Seconds() - now.Seconds()) / 24 / 60 / 60
Rust
chrono を使った場合
- let d = Local.with_ymd_and_hms(2010, 1, 3, 0, 0, 0).unwrap().date_naive();
- let days = (Local::now().date_naive() - d).num_days();
Dart
- var now = DateTime.now();
- var d = DateTime(2010, 1, 3, now.hour, now.minute, now.second, now.millisecond);
- var days = now.difference(d).inDays;
TypeScript
- let now = new Date();
- let d = new Date(2010, 0, 3, now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds());
- let days = (now.getTime() - d.getTime()) / 24 / 60 / 60 / 1000;
Moment.js を使った場合
- let m = moment([2010, 0, 3]);
- let days = moment().diff(m, 'day');
- let m = moment({ year: 2010, month: 0, day: 3 });
- let days = moment().diff(m, 'day');
JavaScript
- let now = new Date();
- let d = new Date(2010, 0, 3, now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds());
- let days = (now.getTime() - d.getTime()) / 24 / 60 / 60 / 1000;
Moment.js を使った場合
- let m = moment([2010, 0, 3]);
- let days = moment().diff(m, 'day');
- let m = moment({ year: 2010, month: 0, day: 3 });
- let days = moment().diff(m, 'day');
CoffeeScript
- now = new Date
- d = new Date 2010, 0, 3, now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds()
- days = (now.getTime() - d.getTime()) / 24 / 60 / 60 / 1000
Moment.js を使った場合
- m = moment [2010, 0, 3]
- days = moment().diff m, 'day'
- m = moment year: 2010, month: 0, day: 3
- days = moment().diff m, 'day'
Ruby
- d = Time.local 2010, 1, 3
- days = ((Time.today - d) / 24 / 60 / 60).to_i
Ruby on Rails の場合
- d = Time.local 2010, 1, 3
- days = ((Time.today - d) / 1.day).to_i
Python
- d = date(2010, 1, 3)
- days = (date.today() - d).days
PHP
- $d = new DateTime();
- $d->setDate(2010, 1, 3);
- $d->setTime(0, 0);
- $today = new DateTime('today');
- $days = intval($today->diff($d)->format('%r%a'));
Perl
- my $now = time;
- my $nowObj = localtime $now;
- my $t = timelocal $nowObj->sec, $nowObj->min, $nowObj->hour, 3, 0, 2010;
- my $days = ($now - $t) / 24 / 60 / 60;
CPAN の
Date::Simple を使った場合
- my $today = Date::Simple::today;
- my $d = Date::Simple::ymd 2010, 1, 3;
- my $days = $today - $d;
Java
- LocalDateTime dt = LocalDateTime.of(2010, 1, 3, 12, 34, 56);
- boolean isPast = dt.isBefore(LocalDateTime.now());
Groovy
- def dt = LocalDateTime.of(2010, 1, 3, 12, 34, 56)
- def isPast = dt.isBefore(LocalDateTime.now())
Kotlin
- val dt = LocalDateTime.of(2010, 1, 3, 12, 34, 56)
- val isPast = dt.isBefore(LocalDateTime.now)
Scala
- val dt = LocalDateTime.of(2010, 1, 3, 12, 34, 56)
- val isPast = dt.isBefore(LocalDateTime.now)
Scala-Time を使った場合
- val dt = new DateMidnight(2010, 1, 3).toDateTime + 12.hours + 34.minutes + 56.seconds
- val isPast = dt.isBeforeNow
- val dt = new DateMidnight(2010, 1, 3).toDateTime + 12.hours + 34.minutes + 56.seconds
- val isPast = dt < DateTime.now
Erlang
- Now = erlang:localtime(),
- T = {{2010, 1, 3}, {12, 34, 56}},
- IsPast = T < Now.
Haskell
- tz <- getCurrentTimeZone
- now <- getCurrentTime
- let d = LocalTime (fromGregorian 2010 1 3) (TimeOfDay 12 34 56)
- let isPast = d < utcToLocalTime tz now
- tz <- getCurrentTimeZone
- now <- getCurrentTime
- let d = localTimeToUTC tz $ LocalTime (fromGregorian 2010 1 3) (TimeOfDay 12 34 56)
- let isPast = d < now
PowerShell
- $d = New-Object DateTime 2010, 1, 3, 12, 34, 56
- $isPast = $d -lt (date)
- $d = date -Year 2010 -Month 1 -Day 3 -Hour 12 -Minute 34 -Second 56
- $isPast = $d -lt (date)
F#
- let d = new System.DateTime(2010, 1, 3, 12, 34, 56)
- let isPast = d < System.DateTime.Now
C#
- DateTime d = new DateTime(2010, 1, 3, 12, 34, 56);
- bool isPast = d < DateTime.now;
C++
Boost を使った場合
- #include <boost/date_time/posix_time/posix_time.hpp>
- #include <boost/date_time/gregorian/gregorian.hpp>
- ptime d(boost::gregorian::date(2010, 1, 3), time_duration(12, 34, 56));
- bool is_past = d < second_clock::local_time();
Go
- now := time.LocalTime()
- d := *now
- d.Year, d.Month, d.Day = 2010, 1, 3
- d.Hour, d.Minute, d.Second = 12, 34, 56
- isPast := d.Seconds() < now.Seconds()
Rust
chrono を使った場合
- let d = Local.with_ymd_and_hms(2010, 1, 3, 12, 34, 56).unwrap();
- let is_past = d < Local::now();
Dart
- var now = DateTime.now();
- var d = DateTime(2010, 1, 3, 12, 34, 56);
- var isPast = d.isBefore(now);
TypeScript
- let now = new Date();
- let d = new Date(2010, 0, 3, 12, 34, 56);
- let isPast = d.getTime() < now.getTime();
Moment.js を使った場合
- let m = moment([2010, 0, 3, 12, 34, 56]);
- let isPast = m.isBefore(moment());
JavaScript
- let now = new Date();
- let d = new Date(2010, 0, 3, 12, 34, 56);
- let isPast = d.getTime() < now.getTime();
Moment.js を使った場合
- let m = moment([2010, 0, 3, 12, 34, 56]);
- let isPast = m.isBefore(moment());
CoffeeScript
- now = new Date
- d = new Date 2010, 0, 3, 12, 34, 56
- isPast = d.getTime() < now.getTime()
Moment.js を使った場合
- m = moment [2010, 0, 3, 12, 34, 56]
- isPast = m.isBefore moment()
Ruby
- d = Time.local 2010, 1, 3, 12, 34, 56
- is_past = d < Time.now
Python
- d = datetime(2010, 1, 3, 12, 34, 56)
- is_past = d < datetime.now()
PHP
- $d = new DateTime();
- $d->setDate(2010, 1, 3);
- $d->setTime(12, 34, 56);
- $isPast = $d->diff(new DateTime())->format('%R') === '+';
Perl
- my $t = timelocal 56, 34, 12, 3, 0, 2010;
- my $isPast = $t < time;