bat Windows gets the current time

bat Windows gets the current time

Get method differences

Getting the year, month and day may look like this:

获取年:yyyy=%date:~,4%
获取月:mm=%date:~5,2%
获取日:day=%date:~8,2% 

It might be something like this:

获取年:%date:~3,4%
获取月:%date:~8,2%
获取日:%date:~11,2%

Why do everyone get the year, month and day in different ways? Which method should we use ourselves?

How to choose based on

First of all, how do you understand %date:~3,4%? Indicates that the %date% string is intercepted, starting from index 3 and intercepting 4 characters thereafter. (index starts from 0)

Secondly, use the following command to check the windows time (%date%):

C:\Users\admin>echo %date%
周三 2023/05/24
C:\Users\admin>

As above, I apply to the second case.

You can see that there is a week in front of the time. If you don’t want the week, you can do it by intercepting (starting from the fourth digit, that is, the index is 3, and intercepting the next 10 digits):

C:\Users\admin>echo %date:~3,10% 
2023/05/24
C:\Users\admin>

What should I do if the time format yyyy/MM/dd does not meet the requirements? customize!

截取年份:%date:~3,4%  ---> 2023
截取月份:%date:~8,2%  ---> 05
截取日期:%date:~11,2% ---> 24
自定义时间格式为yyyy-MM-dd:%date:~3,4%-%date:~8,2%-%date:~11,2%

看一下结果:
C:\Users\admin>echo %date:~3,4%-%date:~8,2%-%date:~11,2%
2023-05-24
C:\Users\admin>

Use and test

A simple bat:

@echo off

rem 根据当前日期获取,年月日串
set yyyy=%date:~3,4%
set mm=%date:~8,2%
set day=%date:~11,2% 
set currentDate=%yyyy%-%mm%-%day%

echo %currentDate%

Results of the:

2023-05-24

Guess you like

Origin blog.csdn.net/weixin_46505978/article/details/130847518
Recommended