PHP/Python/Java获取当前时间的用法

PHP

在PHP中获取当前时间并赋值给对象属性,可以使用以下方法:

方法1:获取当前时间戳(整数)

$myData->train_begin_time = time(); 
// 输出示例:1717380000(Unix时间戳)

方法2:获取格式化日期字符串

$myData->train_begin_time = date('Y-m-d H:i:s');
// 输出示例:"2024-06-03 15:30:45"

方法3:使用DateTime对象

$myData->train_begin_time = new DateTime();
// 输出:DateTime对象(需要后续格式化

JavaScript

// 基础时间对象
const now = new Date();

// 获取时间戳(毫秒)
const timestamp = Date.now(); 

// 获取各时间分量
const year = now.getFullYear();    // 2023
const month = now.getMonth() + 1;  // 1-12(注意补0)
const day = now.getDate();         // 1-31
const hours = now.getHours();      // 0-23
const minutes = now.getMinutes();  // 0-59
const seconds = now.getSeconds();  // 0-59

// 格式化输出
const isoString = now.toISOString();       // "2023-12-25T08:30:15.123Z"
const localeString = now.toLocaleString(); // "2023/12/25 16:30:15"(根据系统区域)

// 第三方库(推荐)
import moment from 'moment';
moment().format('YYYY-MM-DD HH:mm:ss'); // "2023-12-25 16:30:15"

Python

from datetime import datetime
import time

# 获取当前时间对象
now = datetime.now()

# 获取时间戳(秒级浮点数)
timestamp = time.time()  # 1671964215.123456

# 获取各时间分量
year = now.year        # 2023
month = now.month      # 1-12
day = now.day          # 1-31
hour = now.hour        # 0-23
minute = now.minute    # 0-59
second = now.second    # 0-59

# 格式化输出
formatted = now.strftime("%Y-%m-%d %H:%M:%S")  # "2023-12-25 16:30:15"
iso_format = now.isoformat()                    # "2023-12-25T16:30:15.123456"

# 时区处理(需安装pytz)
from pytz import timezone
tz_shanghai = timezone('Asia/Shanghai')
now_tz = datetime.now(tz_shanghai)

Java

import java.time.*;

// Java 8+ 时间API(推荐)
LocalDateTime now = LocalDateTime.now();
ZonedDateTime nowWithZone = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));

// 获取时间分量
int year = now.getYear();        // 2023
Month month = now.getMonth();    // DECEMBER
int day = now.getDayOfMonth();   // 25
int hour = now.getHour();        // 16

// 格式化输出
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatted = now.format(formatter);  // "2023-12-25 16:30:15"

// 传统方式(不推荐)
Date oldDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String oldFormatted = sdf.format(oldDate);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值