1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

DateTime Prob

Discussion in 'PHP' started by vOlLvEriNe, Aug 3, 2015.

  1. #1
    Hello Guys, I Have Prob
            $now = new DateTime('now');
            $now->setTimezone(new DateTimeZone('Asia/Karachi'));
            echo $now->format('c');
    PHP:
    This code show me date something like this 2015-08-04T03:49:25+05:00, Thats Correct, But actually I need timestamp, with Asia/Karachi timezone, So when I change echo $now->format('c'); to echo $now->getTimestamp(); output is 1438642165, But when I convert this timestamp to readable time, I got this 2015-08-03T22:49:25+00:00, which is incorrect, please help me to get correct timestamp
    Sorry for bad English
     
    vOlLvEriNe, Aug 3, 2015 IP
  2. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #2
    You are probably converting that timestamp incorrectly or without reference to the timezone you have:

    
    $now = new DateTime('now');
    $now->setTimezone(new DateTimeZone('Asia/Karachi'));
    echo $now->format('c').PHP_EOL;
    
    $time = $now->getTimestamp();
    echo $time.PHP_EOL;
    
    $now = new DateTime();
    $now->setTimestamp($time);
    echo $now->format('c').PHP_EOL;
    
    /*
    2015-08-04T05:01:48+05:00
    1438646508
    2015-08-03T17:01:48-07:00
    */
    
    Code (markup):
    You need to insure that the timezone is set before you output the time like so:

    
    $now = new DateTime('now');
    $now->setTimezone(new DateTimeZone('Asia/Karachi'));
    echo $now->format('c').PHP_EOL;
    
    $time = $now->getTimestamp();
    echo $time.PHP_EOL;
    
    $now = new DateTime();
    $now->setTimezone(new DateTimeZone('Asia/Karachi'));
    $now->setTimestamp($time);
    echo $now->format('c').PHP_EOL;
    
    /*
    2015-08-04T04:58:28+05:00
    1438646308
    2015-08-04T04:58:28+05:00
    */
    
    Code (markup):
    You can see that the timestamp you have reflects the timezone you have set.
     
    ThePHPMaster, Aug 3, 2015 IP
  3. vOlLvEriNe

    vOlLvEriNe Member

    Messages:
    99
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #3
    If I get timestamp from db, then should I set the timezone again ?
     
    vOlLvEriNe, Aug 3, 2015 IP
  4. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #4
    Yes, you will have to to get the correct time you want.
     
    ThePHPMaster, Aug 4, 2015 IP