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

如何用JavaScript转换日期格式以计算上次登录间隔天数?

Calculate Days Since Last Login with String Date Input

Got it, let's break down how to adapt that code to your actual scenario. Here's what you need to do:

Step 1: Convert the string date to a valid Date object

Your last login date is in the format "2020-03-06 18:20:36:187" (YYYY-MM-DD HH:mm:ss:SSS). Modern JavaScript Date constructors can usually parse this format directly, but if you want to lock in maximum compatibility (especially for older browsers or Node.js versions), you can tweak the string to match the ISO 8601 standard first:

// Option 1: Direct parsing (works in most modern environments)
const lastLoginStr = "2020-03-06 18:20:36:187";
const lastLoginDate = new Date(lastLoginStr);

// Option 2: Convert to ISO 8601 for universal compatibility
const isoLastLoginStr = lastLoginStr.replace(' ', 'T').replace(/:(\d{3})$/, '.$1');
const lastLoginDate = new Date(isoLastLoginStr);

Step 2: Get the current date

Grabbing the current date is super straightforward—just create a new Date instance without any arguments:

const currentDate = new Date();

Step 3: Calculate the difference in days

Now plug these two Date objects into the logic you found earlier. Here's the full working code:

const oneDay = 24 * 60 * 60 * 1000; // Total milliseconds in one day

// Convert string date to Date object
const lastLoginStr = "2020-03-06 18:20:36:187";
const lastLoginDate = new Date(lastLoginStr);

// Get current date
const currentDate = new Date();

// Calculate and round the day difference
const diffDays = Math.round(Math.abs((currentDate - lastLoginDate) / oneDay));

console.log(`Days since last login: ${diffDays}`);

Quick tip on rounding

Using Math.round gives you the nearest whole number of days. If you want to count only full days passed (ignore partial days), swap it with Math.floor. If you want to count any partial day as a full day, use Math.ceil instead.

内容的提问来源于stack exchange,提问作者Divya Agrawal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 21:32:43