Exciting news! TCMS official website is live! Offering full-stack software services including enterprise-level custom R&D, App and mini-program development, multi-system integration, AI, blockchain, and embedded development, empowering digital-intelligent transformation across industries. Visit dev.tekin.cn to discuss cooperation!

Implementing Human-Readable Time Difference Calculation in Multiple Languages -- Code Examples in Python, Go, PHP, Rust, and JavaScript

2025-05-03 28 mins read

Across the six programming language implementations, the core logic for calculating human-readable time differences is consistent—with variations only in syntax and the use of time-processing libraries. Python code is concise and readable, suitable for rapid development and scripting; JavaScript is ideal for front-end or Node.js environments; PHP is commonly used for server-side development;

mplementing-Human-Readable-Time-Difference-Calculation-in-Multiple-Languages-
    

Introduction

In many applications, displaying a human-readable time difference between two time points is a common requirement—such as showing the post time of messages on social platforms or recording event intervals in logging systems. This article details how to implement human-readable time difference calculation in six different programming languages (Python, JavaScript, PHP, Rust, Go, and Java), supporting both Chinese and English output and allowing users to choose whether to use "weeks" as a time unit.

Implementation

The overall implementation approach is to first calculate the time difference between two time points (in seconds), then select the most appropriate time unit based on preset thresholds, and format the result into a human-readable string. The specific steps are as follows:

  1. Calculate Time Difference : Obtain the time difference in seconds between the two time points.

  2. Define Time Unit Thresholds : Define the second thresholds corresponding to different time units (e.g., year, month, week, day, hour, minute).

  3. Select Appropriate Time Unit : Based on the time difference and thresholds, select the most suitable time unit and calculate the quantity in that unit.

  4. Format Output : Combine the quantity and time unit into a human-readable string according to the user-selected language (Chinese or English).

Python Implementation

from datetime import datetime

def human_readable_time_diff(
   start_time: datetime,
   end_time: datetime,
   language: str = 'zh',
   use_weeks: bool = True
) -> str:
   """
  Calculate the human-readable time difference between two time points

  :param start_time: Start time
  :param end_time: End time
  :param language: Output language ('zh' for Chinese/'en' for English)
  :param use_weeks: Whether to use "week" as a time unit
  :return: Human-readable time difference string
  """
   # Calculate the time difference in seconds
   delta = end_time - start_time
   delta_seconds = abs(delta.total_seconds())

   # Define time units with their corresponding seconds and thresholds
   units = [
      ('year', 365 * 24 * 60 * 60, 365),
      ('month', 30 * 24 * 60 * 60, 30),
      ('week', 7 * 24 * 60 * 60, 7) if use_weeks else None,
      ('day', 24 * 60 * 60, 1),
      ('hour', 60 * 60, 1/24),
      ('minute', 60, 1/1440),
  ]

   # Filter out None values to keep only valid time units
   units = [u for u in units if u is not None]

   # Iterate through units to find the appropriate one
   for unit_info in units:
       unit, seconds, _ = unit_info
       if delta_seconds >= seconds:
           # Calculate the quantity for the selected unit
           count = int(delta_seconds // seconds)
           return format_output(count, unit, language)

   # If time difference is less than 1 minute, return corresponding result based on language
   return '刚刚' if language == 'zh' else 'just now'

def format_output(count: int, unit: str, language: str) -> str:
   """Format the output string"""
   if language == 'zh':
       # Chinese time unit mapping
       units_zh = {
           'year': '年',
           'month': '个月',
           'week': '周',
           'day': '天',
           'hour': '小时',
           'minute': '分钟'
      }
       return f"{count}{units_zh[unit]}前"
   else:
       # Handle English pluralization
       unit_en = unit if count == 1 else f"{unit}s"
       return f"{count} {unit_en} ago"

# Usage example
start = datetime(2024, 3, 20, 10, 0, 0)
end = datetime(2024, 3, 20, 11, 30, 0)

print(human_readable_time_diff(start, end))                   # Output: 1小时前
print(human_readable_time_diff(start, end, language='en'))    # Output: 1 hour ago
print(human_readable_time_diff(start, end, use_weeks=False))  # Output: 1小时前

Time Complexity Analysis : The time complexity of the Python implementation is O (1). The length of the units list is fixed and does not change with input size. Traversing this list involves a constant number of operations to find the appropriate time unit, resulting in constant time complexity.

JavaScript Implementation

function humanReadableTimeDiff(startTime, endTime, language = 'zh', useWeeks = true) {
   // Calculate the time difference in seconds
   const deltaSeconds = Math.abs((endTime - startTime) / 1000);
   // Define time units with their corresponding seconds and thresholds
   const units = [
      { unit: 'year', seconds: 365 * 24 * 60 * 60, threshold: 365 },
      { unit: 'month', seconds: 30 * 24 * 60 * 60, threshold: 30 },
       useWeeks ? { unit: 'week', seconds: 7 * 24 * 60 * 60, threshold: 7 } : null,
      { unit: 'day', seconds: 24 * 60 * 60, threshold: 1 },
      { unit: 'hour', seconds: 60 * 60, threshold: 1 / 24 },
      { unit: 'minute', seconds: 60, threshold: 1 / 1440 }
  ].filter(u => u !== null);

   // Iterate through units to find the appropriate one
   for (const unitInfo of units) {
       if (deltaSeconds >= unitInfo.seconds) {
           // Calculate the quantity for the selected unit
           const count = Math.floor(deltaSeconds / unitInfo.seconds);
           return formatOutput(count, unitInfo.unit, language);
      }
  }

   // If time difference is less than 1 minute, return corresponding result based on language
   return language === 'zh' ? '刚刚' : 'just now';
}

function formatOutput(count, unit, language) {
   if (language === 'zh') {
       // Chinese time unit mapping
       const unitsZh = {
           year: '年',
           month: '个月',
           week: '周',
           day: '天',
           hour: '小时',
           minute: '分钟'
      };
       return `${count}${unitsZh[unit]}前`;
  } else {
       // Handle English pluralization
       const unitEn = count === 1 ? unit : `${unit}s`;
       return `${count} ${unitEn} ago`;
  }
}

// Usage example
const start = new Date(2024, 2, 20, 10, 0, 0);
const end = new Date(2024, 2, 20, 11, 30, 0);
console.log(humanReadableTimeDiff(start, end));
console.log(humanReadableTimeDiff(start, end, 'en'));
console.log(humanReadableTimeDiff(start, end, 'zh', false));

Time Complexity Analysis : The time complexity of the JavaScript implementation is also O (1). The length of the units array is fixed, and traversing it to find the appropriate time unit involves a constant number of operations regardless of input size.

Compact Version

// Function to calculate the human-readable time difference
function timeAgo(dateString) {
const lastUpdate = new Date(dateString);
const now = new Date();
const diffTime = now - lastUpdate; // Difference in milliseconds

const diffSeconds = Math.floor(diffTime / 1000);
const diffMinutes = Math.floor(diffSeconds / 60);
const diffHours = Math.floor(diffMinutes / 60);
const diffDays = Math.floor(diffHours / 24);
const diffMonths = Math.floor(diffDays / 30);
const diffYears = Math.floor(diffMonths / 12);

if (diffYears > 0) {
return diffYears === 1 ? '1 year ago' : `${diffYears} years ago`;
} else if (diffMonths > 0) {
return diffMonths === 1 ? '1 month ago' : `${diffMonths} months ago`;
} else if (diffDays > 0) {
return diffDays === 1 ? '1 day ago' : `${diffDays} days ago`;
} else if (diffHours > 0) {
return diffHours === 1 ? '1 hour ago' : `${diffHours} hours ago`;
} else if (diffMinutes > 0) {
return diffMinutes === 1 ? '1 minute ago' : `${diffMinutes} minutes ago`;
} else {
return 'just now';
}
}

PHP Implementation

<?php
function humanReadableTimeDiff($startTime, $endTime, $language = 'zh', $useWeeks = true) {
   // Calculate the time difference in seconds
   $deltaSeconds = abs(strtotime($endTime) - strtotime($startTime));
   // Define time units with their corresponding seconds and thresholds
   $units = [
      ['unit' => 'year', 'seconds' => 365 * 24 * 60 * 60, 'threshold' => 365],
      ['unit' => 'month', 'seconds' => 30 * 24 * 60 * 60, 'threshold' => 30],
       $useWeeks ? ['unit' => 'week', 'seconds' => 7 * 24 * 60 * 60, 'threshold' => 7] : null,
      ['unit' => 'day', 'seconds' => 24 * 60 * 60, 'threshold' => 1],
      ['unit' => 'hour', 'seconds' => 60 * 60, 'threshold' => 1 / 24],
      ['unit' => 'minute', 'seconds' => 60, 'threshold' => 1 / 1440]
  ];
   // Filter out null values to keep only valid time units
   $units = array_filter($units);

   // Iterate through units to find the appropriate one
   foreach ($units as $unitInfo) {
       if ($deltaSeconds >= $unitInfo['seconds']) {
           // Calculate the quantity for the selected unit
           $count = floor($deltaSeconds / $unitInfo['seconds']);
           return formatOutput($count, $unitInfo['unit'], $language);
      }
  }

   // If time difference is less than 1 minute, return corresponding result based on language
   return $language === 'zh' ? '刚刚' : 'just now';
}

function formatOutput($count, $unit, $language) {
   if ($language === 'zh') {
       // Chinese time unit mapping
       $unitsZh = [
           'year' => '年',
           'month' => '个月',
           'week' => '周',
           'day' => '天',
           'hour' => '小时',
           'minute' => '分钟'
      ];
       return $count . $unitsZh[$unit] . '前';
  } else {
       // Handle English pluralization
       $unitEn = $count === 1 ? $unit : $unit . 's';
       return $count . ' ' . $unitEn . ' ago';
  }
}

// Usage example
$start = '2024-03-20 10:00:00';
$end = '2024-03-20 11:30:00';
echo humanReadableTimeDiff($start, $end) . "\n";
echo humanReadableTimeDiff($start, $end, 'en') . "\n";
echo humanReadableTimeDiff($start, $end, 'zh', false) . "\n";

?>

Time Complexity Analysis : The time complexity of the PHP implementation is O (1). The length of the units array is fixed, and filtering and traversing it involve a constant number of operations independent of input size.

Rust Implementation

use chrono::{DateTime, Utc};

fn human_readable_time_diff(start_time: DateTime<Utc>, end_time: DateTime<Utc>, language: &str, use_weeks: bool) -> String {
   // Calculate the time difference in seconds
   let delta_seconds = (end_time - start_time).num_seconds().abs();
   // Define time units with their corresponding seconds and thresholds
   let units = [
      ("year", 365 * 24 * 60 * 60, 365),
      ("month", 30 * 24 * 60 * 60, 30),
       if use_weeks { Some(("week", 7 * 24 * 60 * 60, 7)) } else { None },
      ("day", 24 * 60 * 60, 1),
      ("hour", 60 * 60, 1 / 24),
      ("minute", 60, 1 / 1440)
  ].into_iter().filter_map(|x| x).collect::<Vec<_>>();

   // Iterate through units to find the appropriate one
   for (unit, seconds, _) in units {
       if delta_seconds >= *seconds {
           // Calculate the quantity for the selected unit
           let count = (delta_seconds / *seconds) as usize;
           return format_output(count, unit, language);
      }
  }

   // If time difference is less than 1 minute, return corresponding result based on language
   if language == "zh" {
       "刚刚".to_string()
  } else {
       "just now".to_string()
  }
}

fn format_output(count: usize, unit: &str, language: &str) -> String {
   if language == "zh" {
       // Chinese time unit mapping
       let units_zh = [
          ("year", "年"),
          ("month", "个月"),
          ("week", "周"),
          ("day", "天"),
          ("hour", "小时"),
          ("minute", "分钟")
      ];
       let unit_zh = units_zh.iter().find(|(u, _)| *u == unit).unwrap().1;
       format!("{}{}前", count, unit_zh)
  } else {
       // Handle English pluralization
       let unit_en = if count == 1 {
           unit.to_string()
      } else {
           format!("{}s", unit)
      };
       format!("{} {} ago", count, unit_en)
  }
}

fn main() {
   let start = Utc.ymd(2024, 3, 20).and_hms(10, 0, 0);
   let end = Utc.ymd(2024, 3, 20).and_hms(11, 30, 0);
   println!("{}", human_readable_time_diff(start, end, "zh", true));
   println!("{}", human_readable_time_diff(start, end, "en", true));
   println!("{}", human_readable_time_diff(start, end, "zh", false));
}

Time Complexity Analysis : The time complexity of the Rust implementation is O (1). The vector derived from the units array has a fixed length, and traversing it involves a constant number of operations regardless of input size.

Go Implementation

package main

import (
   "fmt"
   "time"
)

func humanReadableTimeDiff(startTime, endTime time.Time, language string, useWeeks bool) string {
   // Calculate the time difference in seconds
   deltaSeconds := int64(endTime.Sub(startTime).Seconds())
   if deltaSeconds < 0 {
       deltaSeconds = -deltaSeconds
  }
   // Define time units with their corresponding seconds and thresholds
   units := []struct {
       unit      string
       seconds   int64
       threshold float64
  }{
      {"year", 365 * 24 * 60 * 60, 365},
      {"month", 30 * 24 * 60 * 60, 30},
      {
           "week", 7 * 24 * 60 * 60, 7,
      },
      {"day", 24 * 60 * 60, 1},
      {"hour", 60 * 60, 1 / 24},
      {"minute", 60, 1 / 1440},
  }
   // Remove week unit if not needed
   if !useWeeks {
       units = append(units[:2], units[3:]...)
  }

   // Iterate through units to find the appropriate one
   for _, unitInfo := range units {
       if deltaSeconds >= unitInfo.seconds {
           // Calculate the quantity for the selected unit
           count := deltaSeconds / unitInfo.seconds
           return formatOutput(int(count), unitInfo.unit, language)
      }
  }

   // If time difference is less than 1 minute, return corresponding result based on language
   if language == "zh" {
       return "刚刚"
  }
   return "just now"
}

func formatOutput(count int, unit string, language string) string {
   if language == "zh" {
       // Chinese time unit mapping
       unitsZh := map[string]string{
           "year":   "年",
           "month":  "个月",
           "week":   "周",
           "day":    "天",
           "hour":   "小时",
           "minute": "分钟",
      }
       return fmt.Sprintf("%d%s前", count, unitsZh[unit])
  }
   // Handle English pluralization
   unitEn := unit
   if count > 1 {
       unitEn = fmt.Sprintf("%ss", unit)
  }
   return fmt.Sprintf("%d %s ago", count, unitEn)
}

func main() {
   start := time.Date(2024, 3, 20, 10, 0, 0, 0, time.UTC)
   end := time.Date(2024, 3, 20, 11, 30, 0, 0, time.UTC)
   fmt.Println(humanReadableTimeDiff(start, end, "zh", true))
   fmt.Println(humanReadableTimeDiff(start, end, "en", true))
   fmt.Println(humanReadableTimeDiff(start, end, "zh", false))
}

Time Complexity Analysis : The time complexity of the Go implementation is O (1). The length of the units slice is fixed (even after removing the week unit if needed), and traversing it involves a constant number of operations independent of input size.

Java Implementation

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

class TimeDifferenceFormatter {

   public static String humanReadableTimeDiff(LocalDateTime startTime, LocalDateTime endTime, String language, boolean useWeeks) {
       // Calculate the time difference in seconds
       Duration duration = Duration.between(startTime, endTime);
       long deltaSeconds = Math.abs(duration.getSeconds());

       // Define time units with their corresponding seconds and thresholds
       List<TimeUnitInfo> units = new ArrayList<>();
       units.add(new TimeUnitInfo("year", 365 * 24 * 60 * 60, 365));
       units.add(new TimeUnitInfo("month", 30 * 24 * 60 * 60, 30));
       if (useWeeks) {
           units.add(new TimeUnitInfo("week", 7 * 24 * 60 * 60, 7));
      }
       units.add(new TimeUnitInfo("day", 24 * 60 * 60, 1));
       units.add(new TimeUnitInfo("hour", 60 * 60, 1.0 / 24));
       units.add(new TimeUnitInfo("minute", 60, 1.0 / (24 * 60)));

       // Iterate through units to find the appropriate one
       for (TimeUnitInfo unitInfo : units) {
           if (deltaSeconds >= unitInfo.seconds) {
               // Calculate the quantity for the selected unit
               long count = deltaSeconds / unitInfo.seconds;
               return formatOutput(count, unitInfo.unit, language);
          }
      }

       // If time difference is less than 1 minute, return corresponding result based on language
       return language.equals("zh") ? "刚刚" : "just now";
  }

   private static String formatOutput(long count, String unit, String language) {
       if (language.equals("zh")) {
           // Chinese time unit mapping
           String[] unitsZh = {"年", "个月", "周", "天", "小时", "分钟"};
           String[] unitNames = {"year", "month", "week", "day", "hour", "minute"};
           for (int i = 0; i < unitNames.length; i++) {
               if (unitNames[i].equals(unit)) {
                   return count + unitsZh[i] + "前";
              }
          }
      } else {
           // Handle English pluralization
           String unitEn = count == 1 ? unit : unit + "s";
           return count + " " + unitEn + " ago";
      }
       return "";
  }

   static class TimeUnitInfo {
       String unit;
       long seconds;
       double threshold;

       TimeUnitInfo(String unit, long seconds, double threshold) {
           this.unit = unit;
           this.seconds = seconds;
           this.threshold = threshold;
      }
  }

   public static void main(String[] args) {
       LocalDateTime start = LocalDateTime.of(2024, 3, 20, 10, 0, 0);
       LocalDateTime end = LocalDateTime.of(2024, 3, 20, 11, 30, 0);
       System.out.println(humanReadableTimeDiff(start, end, "zh", true));
       System.out.println(humanReadableTimeDiff(start, end, "en", true));
       System.out.println(humanReadableTimeDiff(start, end, "zh", false));
  }
}

Time Complexity Analysis : The time complexity of the Java implementation is O (1). The length of the units list is fixed, and traversing it involves a constant number of operations regardless of input size.

Summary

Across the six programming language implementations, the core logic for calculating human-readable time differences is consistent—with variations only in syntax and the use of time-processing libraries. Python code is concise and readable, suitable for rapid development and scripting; JavaScript is ideal for front-end or Node.js environments; PHP is commonly used for server-side development; Rust is known for its high performance and safety; Go excels in concurrent processing and network programming; and Java is widely adopted in enterprise-level development due to its cross-platform capabilities and robust ecosystem. All six implementations have a time complexity of O (1), ensuring high efficiency for time difference calculations without significant performance degradation as input size increases. You can choose the appropriate language and implementation based on your project requirements.

TAG

Python, JavaScript, PHP, Rust, Go, Java, Time Difference Calculation, Human-Readable Time Difference, Time Complexity Analysis

Image NewsLetter
Icon primary
Newsletter

Subscribe our newsletter

Please enter your email address below and click the subscribe button. By doing so, you agree to our Terms and Conditions.

Your experience on this site will be improved by allowing cookies Cookie Policy