Free coupon for initial registration

Get date of X days ago (example: 2 days ago)

Contents [hide]

Output

2021/03/25

Programming code example

Go

1
2
3
4
5
6
7
8
package main
import "fmt"
import "time"
  
func main() {
    jst, _ := time.LoadLocation("Asia/Tokyo")
    fmt.Println(time.Now().Add(-2*24*time.Hour).In(jst).Format("2006/01/02"))
}

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
console.log(get_x_days_ago(2));
 
function get_x_days_ago(x){
    var date = new Date();
    return formatDate(date.setDate(date.getDate() - x));
}
 
function formatDate(date) {
    var d = new Date(date),
    month = '' + (d.getMonth() + 1),
    day = '' + d.getDate(),
    year = d.getFullYear();
    if (month.length < 2)
        month = '0' + month;
    if (day.length < 2)
        day = '0' + day;
    return [year, month, day].join('/');
}

Perl

1
2
my ($s, $mi, $h, $d, $m, $y) = localtime(time - 2 * 24 * 60 * 60);
print sprintf("%4d/%02d/%02d", $y + 1900, $m + 1, $d)."\n";

PHP

1
2
<?php
echo date('Y/m/d', strtotime('2 days ago'))."\n";

Python

1
2
3
4
5
6
7
from datetime import datetime, timedelta
 
def get_xdays_ago(days_ago):
    x_days_ago = datetime.now() - timedelta(days=days_ago)
    return x_days_ago
 
print( get_xdays_ago(2).strftime("%Y/%m/%d") )

Ruby

1
2
3
require "date"
d = Date.today - 2
puts d.strftime("%Y/%m/%d")

Rust

Corgo.toml

1
2
3
4
5
6
7
8
9
10
[package]
name = "x_days_ago"
version = "0.0.1"
 
[dependencies]
chrono = "0.4"
 
[[bin]]
name = "x_days_ago"
path = "x_days_ago.rs"
Programming code
1
2
3
4
5
6
7
extern crate chrono;
use chrono::{Duration, Local, DateTime};
 
fn main() {
  let date: DateTime<Local> = Local::now() + Duration::days(-2);
  println!("{}", date.format("%Y/%m/%d"))
}

Shell

1
2
3
4
5
6
7
#/bin/sh
date -d "02/01/2000" 2>: 1>:; INVALID=$?;
if [ $INVALID == 1 ]; then
  echo `TZ=+48 date '+%Y/%m/%d'`;
else
  echo `date -d '2 days ago' '+%Y/%m/%d'`;
fi

You can find programming examples to solve same problem using multiple programming languages.
Please find best programming language for your problems and solution.
Covering all cases: JavaScript Perl PHP Python Ruby | Covering some cases: C C++ C# Go Java Rust Shell
 
Big categories
Array | Class | Database | File systems | Network | Number | String | System | Test | Time | Variable
Other useful content
  1. Popular programming languages
  2. Popular web framework
  3. VPS Ranking.com (Find best VPS based on benchmark)
Free coupon for initial registration