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

两类24小时时长校验问题求助:项目修改/验证码重发逻辑故障

Hey there! Let's work through both of your requirements with practical, actionable solutions:

需求1:检查某一项目是否在24小时内被修改

To check if a project (or specific file/directory) was modified within the last 24 hours, you'll need to compare its last modified timestamp against the current time. Here's how to implement this in common languages:

Python Example

import os
from datetime import datetime, timedelta

def is_modified_within_24h(project_path):
    try:
        # Get last modified timestamp (in seconds since epoch)
        last_modified = os.path.getmtime(project_path)
        # Convert to datetime object
        last_modified_time = datetime.fromtimestamp(last_modified)
        # Calculate 24 hours ago from now
        twenty_four_hours_ago = datetime.now() - timedelta(hours=24)
        # Compare times
        return last_modified_time >= twenty_four_hours_ago
    except FileNotFoundError:
        print(f"Error: Project path {project_path} not found")
        return False

# Usage
project_dir = "/path/to/your/project"
if is_modified_within_24h(project_dir):
    print("Project was modified in the last 24 hours")
else:
    print("Project hasn't been modified in the last 24 hours")

Java Example

import java.io.File;
import java.time.Duration;
import java.time.Instant;

public class ProjectModificationChecker {
    public static boolean isModifiedWithin24h(String projectPath) {
        File project = new File(projectPath);
        if (!project.exists()) {
            System.err.println("Error: Project path not found");
            return false;
        }
        
        Instant lastModified = Instant.ofEpochMilli(project.lastModified());
        Instant twentyFourHoursAgo = Instant.now().minus(Duration.ofHours(24));
        
        return lastModified.isAfter(twentyFourHoursAgo);
    }

    public static void main(String[] args) {
        String projectDir = "/path/to/your/project";
        if (isModifiedWithin24h(projectDir)) {
            System.out.println("Project was modified in the last 24 hours");
        } else {
            System.out.println("Project hasn't been modified in the last 24 hours");
        }
    }
}

需求2:验证码24小时有效期校验与重发逻辑

Since you already have the rest of the verification code system working, the key missing piece is tracking each code's creation time and comparing it to the current time. Here's a clear implementation approach:

Core Logic Steps

  1. Store Verification Code Metadata: You need a way to save each user's (or request's) verification code along with its creation timestamp. This can be done with an in-memory dictionary (for small apps) or a database table (for production systems).
  2. Check Expiry on Resend Request: When a user asks to resend the code:
    • Look up their existing code and creation time
    • Calculate the time difference between now and the creation time
    • If the difference is less than 24 hours, return the existing code
    • If it's been over 24 hours (or no existing code exists), generate a new code, update the stored metadata, and return it

Python Example (Using In-Memory Storage)

from datetime import datetime, timedelta
import random
import string

# In-memory storage: key = user identifier (e.g., phone number/email), value = (code, creation_time)
verification_codes = {}

def generate_verification_code(length=6):
    # Generate a random 6-digit numeric code (adjust as needed)
    return ''.join(random.choices(string.digits, k=length))

def get_or_generate_code(user_id):
    current_time = datetime.now()
    # Check if user has an existing code
    if user_id in verification_codes:
        code, creation_time = verification_codes[user_id]
        # Calculate time difference
        time_diff = current_time - creation_time
        if time_diff < timedelta(hours=24):
            # Code is still valid within 24h, return existing
            return code
    # Generate new code if no existing or expired
    new_code = generate_verification_code()
    verification_codes[user_id] = (new_code, current_time)
    return new_code

# Usage
user_phone = "1234567890"
code_to_send = get_or_generate_code(user_phone)
print(f"Sending verification code: {code_to_send}")

Key Notes for Production

  • Persistent Storage: Replace the in-memory dictionary with a database (like PostgreSQL, Redis) so data survives server restarts. Redis is especially good for this since it supports TTL (time-to-live) values, though you'll still need to track creation time explicitly if you want to resend the same code instead of auto-expiring.
  • Timezone Handling: Always use UTC timestamps to avoid timezone discrepancies. For example, replace datetime.now() with datetime.utcnow() and store UTC times.
  • Security: Ensure user identifiers are unique and secure (avoid using plain text if sensitive). Also, consider adding rate limiting to prevent abuse of the resend feature.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:00:09