You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js中将时间戳1518427800转为hh:mm:ss dd/mm/yyyy格式?

Solution: Convert Unix Timestamps to Human-Readable Format in Node.js for Firebase

Got it, let's walk through exactly how to handle this without touching your original web app or SQL backend. Here's a step-by-step approach using Node.js:

1. Read Data from MySQL

First, you'll need to pull the course data (including those Unix timestamps) from MySQL. I recommend using the mysql2 package—it's fast and supports promises, which makes async code cleaner.

Install it first if you haven't:

npm install mysql2

Then, here's a snippet to fetch your course data:

const mysql = require('mysql2/promise');

async function getCourseData() {
  const connection = await mysql.createConnection({
    host: 'your-mysql-host',
    user: 'your-mysql-user',
    password: 'your-mysql-password',
    database: 'your-database-name'
  });

  const [rows] = await connection.execute('SELECT id, course_name, start_time, end_time FROM courses');
  await connection.end();
  
  return rows;
}

2. Convert Unix Timestamps to Human-Readable Format

The timestamp 1518427800 is a second-based Unix timestamp (since JavaScript uses milliseconds for Dates, we'll multiply by 1000 first). You can format it into something like YYYY-MM-DD HH:mm:ss or a locale-specific string using JavaScript's built-in Date object or the Intl.DateTimeFormat API (great for internationalization).

Here's a helper function to handle the conversion:

function formatTimestamp(unixTimestamp) {
  // Handle null/undefined values to avoid errors
  if (!unixTimestamp) return 'N/A';
  
  // Convert seconds to milliseconds
  const date = new Date(unixTimestamp * 1000);
  
  // Option 1: Basic ISO-like format (e.g., 2018-02-12 09:30:00)
  // return date.toISOString().slice(0, 19).replace('T', ' ');
  
  // Option 2: Locale-friendly format (adjust options as needed)
  return new Intl.DateTimeFormat('en-US', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  }).format(date);
}

Now, apply this function to your fetched data:

async function processCourseData() {
  const rawCourses = await getCourseData();
  
  const processedCourses = rawCourses.map(course => ({
    ...course,
    start_time_readable: formatTimestamp(course.start_time),
    end_time_readable: formatTimestamp(course.end_time),
    // Optional: Keep the original timestamp if you need it later for calculations
    original_start_time: course.start_time,
    original_end_time: course.end_time
  }));
  
  return processedCourses;
}

3. Save Processed Data to Firebase

Next, push the transformed data to Firebase. You'll need the firebase-admin SDK for this.

Install it:

npm install firebase-admin

Initialize the SDK (you'll need your service account key from the Firebase Console):

const admin = require('firebase-admin');
const serviceAccount = require('./path-to-your-service-account-key.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'your-firebase-database-url'
});

const db = admin.database();

Then, write the processed data to Firebase:

async function saveToFirebase() {
  const processedCourses = await processCourseData();
  
  const coursesRef = db.ref('courses');
  // You can either set all courses at once, or push them individually if needed
  await coursesRef.set(processedCourses);
  
  console.log('Data successfully saved to Firebase!');
}

// Run the full workflow
saveToFirebase().catch(err => console.error('Error during process:', err));

Key Notes

  • Preserve Original Timestamps: I added original_start_time and original_end_time in the processed data—this is useful if you ever need to do time-based sorting, filtering, or calculations later, since human-readable strings aren't ideal for those tasks.
  • Error Handling: Make sure to wrap async operations in try/catch blocks to handle database connection issues, invalid timestamps, or Firebase write failures.
  • Custom Formatting: Adjust the Intl.DateTimeFormat options to match your needs (e.g., use 'zh-CN' for Chinese locale, add second: '2-digit' if you need to include seconds).

内容的提问来源于stack exchange,提问作者Devanshi Sukhija

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:02:11