Linux: set date through command line

  • How to change the system date in Linux ?

    I want to change:

    • Only Year
    • Only Month
    • Only Date
    • Any combination of above three

    You can use e.g. `date --set='-2 years'` to set the clock back two years, leaving all other elements identical. You can change month and day of month the same way. I haven't checked what happens if that calculation results in a datetime that doesn't actually exist, e.g. during a DST switchover, but the behaviour ought to be identical to the usual "set both date and time to concrete values" behaviour.

    Assuming you're trying to set the date to the current time, you could do `sudo ntpd -gq` to have the system update automatically using the ntp service.

  • Use date -s:

    date -s '2014-12-25 12:34:56'

    Run that as root or under sudo. Changing only one of the year/month/day is more of a challenge and will involve repeating bits of the current date. There are also GUI date tools built in to the major desktop environments, usually accessed through the clock.

    To change only part of the time, you can use command substitution in the date string:

    date -s "2014-12-25 $(date +%H:%M:%S)"

    will change the date, but keep the time. See man date for formatting details to construct other combinations: the individual components are %Y, %m, %d, %H, %M, and %S.

    I don't want to change the time

    There's no option to do that. You can use `date -s "2014-12-25 $(date +%H:%M:%S)"` to change the date and reuse the current time, though.

    came here and hours as well as minutes were matching current time. – nice

    `date: cannot set date: Invalid argument`

    @MichaelHomer @SHW it is possible to change only the date with a command like `date -s 2018-01-01`. Someone shared this in an answer also:

    @baptx On the assumption that it is exactly midnight, yes.

    I try to change but its not changing:- $ sudo date --set="2015-09-30 10:05:59.990" Wed Sep 30 10:05:59 +0530 2015 $ date Thu May 23 15:10:37 +0530 2019

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM