How can I get my correct current local time?

  • I need to get the current time but to be in type DateTime.

    I use:

    DateTime now = System.now();
    

    but it returns wrong time.

    I execute the code in 2017-08-04 00:38:46 AM

    but it returns

    00:38:46:023 USER_DEBUG [138]|DEBUG|now 2017-08-03 21:38:46

    How can I get my correct current local time 2017-08-04 00:38:46?

    I had even tried with:

    DateTime now = DateTime.parse(System.Now().format());
    

    but I still get wrong time.

    01:10:09:021 USER_DEBUG [139]|DEBUG|now 2017-08-03 22:10:00

    How can I get the correct current local time?

    You're asking the wrong question. What are you trying to do?

    I think I've explained it quite clearly. I'm trying to get my local my correct current local time. Apparently it is not working with System.now(); because it is giving me wrong seconds, minutes, hours and days.

    Supplications as to the urgency of your requirement are off topic and also quite rude.

    I am trying to get the correct current time including all components year, month, day hour, minutes and seconds. Because all components are included in **DateTime** that is why I need **DateTime** object.

  • sfdev

    sfdev Correct answer

    4 years ago

    I was trying to get the current Datetime in the local time zone, and found the following solution:

    Datetime now = Datetime.now();
    Integer offset = UserInfo.getTimezone().getOffset(now);
    Datetime local = now.addSeconds(offset/1000);
    

    Interesting. You ignored all of the answers above and posted (and accepted) your own identical answer instead. Not exactly a typical use of this community, for sure.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used