如何使用Moment将字符串格式的时间转换为当日指定时间的Date对象?
Solution to Combine Today's Date with a Given Time String
Hey there, let's tackle this task where we need to merge today's date with a given time string to produce a full timestamp in the format like Sat Mar 19 2022 15:00:00. Here are practical solutions in two widely used languages:
JavaScript Solution
This approach uses native Date object methods to build the desired timestamp:
function getFullTimestamp(timeStr) { // Split input time into hours and minutes (convert to numbers) const [hours, minutes] = timeStr.split(':').map(Number); // Initialize Date object with today's date const currentDate = new Date(); // Update hours/minutes, reset seconds/milliseconds to 0 for consistency currentDate.setHours(hours, minutes, 0, 0); // Return formatted string (trim off timezone suffix if needed) return currentDate.toString().split(' GMT')[0]; } // Test with sample inputs console.log(getFullTimestamp("15:00")); // Outputs e.g., "Sat Mar 19 2022 15:00:00" console.log(getFullTimestamp("11:00")); // Outputs e.g., "Sat Mar 19 2022 11:00:00"
How it works:
- Splits the input time string (like "15:00") into numeric hours and minutes
- Uses the current system date as the base
- Overwrites the hours and minutes with the input values, ensuring seconds/milliseconds are zeroed out
- Converts the Date object to the required string format, removing the default timezone suffix if unnecessary
Python Solution
For Python, we use the built-in datetime module for precise date/time handling:
from datetime import datetime def get_full_timestamp(time_str): # Get today's date (without time) today_date = datetime.today().date() # Parse the input time string into a time object input_time = datetime.strptime(time_str, "%H:%M").time() # Combine today's date with the input time full_datetime = datetime.combine(today_date, input_time) # Format to the exact string pattern needed return full_datetime.strftime("%a %b %d %Y %H:%M:%S") # Test the function print(get_full_timestamp("15:00")) # Outputs 'Sat Mar 19 2022 15:00:00' print(get_full_timestamp("11:00")) # Outputs 'Sat Mar 19 2022 11:00:00'
How it works:
- Extracts the current date (without time components)
- Parses the input time string using
strptimewith the%H:%Mformat (24-hour time) - Combines the date and time into a single datetime object
- Uses
strftimeto format the object into the exact string pattern specified, with abbreviated weekday/month, full year, and zero-padded time values
内容的提问来源于stack exchange,提问作者lecham
相关产品推荐
相关产品推荐

