Sam
Sam

Reputation: 389

only output first characters of variable

I want to make a clock in batch, but when typed echo %time% the decimal seconds are printed as well.
which will output:

15:18:42,15

so i need to get rid of that ,15 but how?

Upvotes: 0

Views: 88

Answers (2)

aschipfl
aschipfl

Reputation: 34909

Here is an alternative way:

for /F "delims=,." %%T in ("%TIME%") do @echo/%%T

The for /F loop iterates once over the time string and splits off the first , or . and everything after.


Anyway, regard that %TIME% (as well as %DATE%) returns a locale-dependent time (or date) string.

To get the current time in a locale-independent manner, use the wmic command:

wmic OS get LocalDateTime

This returns something like:

20180117151842.150000+000

Now let us capture this using for /F and build our own time string, using sub-string expansion:

@echo off
for /F %%D in ('wmic OS get LocalDateTime') do set "DATETIME=%%D"
echo %DATETIME:~8,2%:%DATETIME:~10,2%:%DATETIME:~12,2%

And this always returns, independent on the locale and region settings, something like this:

15:18:42

Upvotes: 2

Stephan
Stephan

Reputation: 56180

you can use substing manipulation, as described in set /?:

echo %time:~0,8%

takes 8 characters, beginning at the first character (zero-based counting)

Upvotes: 3

Related Questions