C++获取当前时间(年月日、时分秒、毫秒)

本文介绍了一种使用C++获取当前时间和日期并将其格式化的方法。通过使用标准库中的time.h,可以轻松地获取到年-月-日、时:分:秒以及毫秒,并展示了一个具体的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mengxiangjia_linxi/article/details/80647284
                                        <div class="markdown_views">
                        <!-- flowchart 箭头图标 勿删 -->
                        <svg xmlns="http://www.w3.org/2000/svg" style="display: none;"><path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path></svg>
                        <p><strong>获取时间:</strong> <br>

年-月-日(YYmmdd)
时:分:秒(HHMMSS)
毫秒(MS)

效率问题需要再优化
代码:

#include <iostream>
#include <string>
#include <time.h>
using namespace std;

struct NowDate
{
    char tmp0[16]; //年月日
    char tmp1[16]; //时分秒
    char tmp2[4];  //毫秒
};

NowDate getTime()
{
    time_t timep;
    time (&timep);
    NowDate date;

    strftime(date.tmp0, sizeof(date.tmp0), "%Y-%m-%d",localtime(&timep) );
    strftime(date.tmp1, sizeof(date.tmp1), "%H:%M:%S",localtime(&timep) );

    struct timeb tb;
    ftime(&tb);     
    sprintf(date.tmp2,"%d",tb.millitm);

    return date;
}

int main()
{
    NowDate time = getTime();
    cout << time.tmp0 <<endl;
    cout << time.tmp1 <<endl;
    cout << time.tmp2 <<endl;

    return 0;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

结果:
这里写图片描述



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值