September 17, 2013

Convert String in Array JQUERY

User2789569’s Question:

I have the data array return of the server :

data.arr = [[Date.UTC(2013, 9, 17),1],[Date.UTC(2013, 9, 18),5],[Date.UTC(2013, 9, 19),2],[Date.UTC(2013, 9, 20),4]]

    [0] "[Date.UTC(2013, 9, 17),1]" String
    [1] "[Date.UTC(2013, 9, 18),5]" String
    [2] "[Date.UTC(2013, 9, 19),2]" String
    [3] "[Date.UTC(2013, 9, 20),4]" String

I need to pass only value to a function that recepeit an array[i,y], i need that stay following; i need to remove the “”.

    [0] [Date.UTC(2013, 9, 17),1]
    [1] [Date.UTC(2013, 9, 18),5]
    [2] [Date.UTC(2013, 9, 19),2]
    [3] [Date.UTC(2013, 9, 20),4]

How to do it?

data.arr = [[Date.UTC(2013, 9, 17),1],[Date.UTC(2013, 9, 18),5],
[Date.UTC(2013, 9, 19),2],[Date.UTC(2013, 9, 20),4]]

This code should already give you a timestamp value, but I am assuming you are asking about when it is treated as string so as suggested in comments, you can use eval to evaluate the string as Data Object.

for(var i = 0; i < data.arr.length; i++) {
     data.arr[i] = [data.arr[i][0], eval(data.arr[i][1])];
}

Here is a demo: http://jsfiddle.net/8eLEH/

March 27, 2013

strftime gets wrong date

Question by crnm

I’m using strftime to display future date.

But while using

strftime('%a., %d. %B %Y',time()+60*60*24*4)

I’m getting Mo., 01. April 2013 instead of Su., 31. March 2013 while using this today.

(Unix timestamp is 1364423120)

strftime('%a., %d. %B %Y',time()+60*60*24*3)

displays the correct Sa., 30. March 2013

What is wrong here with the last day of March?

Answer by Terje D.

The timestamp represents 23:25:20 local time. As daylight savings time comes into effect on March 31th, adding 96 h will give 00:25:20 as local time, thus a date one day later than expected. Using gmstrftime instead of strftime avoids this problem.

<?php

$timestamp = 1364423120;

echo strftime('%a., %d. %B %Y (%c %Z)', $timestamp)."n";
echo strftime('%a., %d. %B %Y (%c %Z)', $timestamp +60*60*24*4)."n";
echo gmstrftime('%a., %d. %B %Y (%c %Z)', $timestamp)."n";
echo gmstrftime('%a., %d. %B %Y (%c %Z)', $timestamp +60*60*24*4)."n";

gives

Wed., 27. March 2013 (Wed Mar 27 23:25:20 2013 CET)
Mon., 01. April 2013 (Mon Apr  1 00:25:20 2013 CEST)
Wed., 27. March 2013 (Wed Mar 27 22:25:20 2013 GMT)
Sun., 31. March 2013 (Sun Mar 31 22:25:20 2013 GMT)

Answer by Starx

According to the manual

strftime — Format a local time/date according to locale settings

Its better if you specify a locale while you are using it, to avoid such problem.

setlocale(LC_TIME, "de_DE");
strftime('%a., %d. %B %Y',time()+60*60*24*4)
March 6, 2013

convert date format within a webservice php context

Question by Peter van der Lely

I am consuming a webservice in php. The piece of code below gives me the following result with regard to the date notation:

Begindatum : 2012-07-02T00:00:00. I would like to have that in a European format like:

Begindatum : 02-07-2012. I’ve been trying to imlement the standard solution:

Convert date format yyyy-mm-dd => dd-mm-yyyy

but without succes. Help is appreceated.

 foreach($array as $k=>$v){
 print "
 <tr>
      <td>
            <ul>
                <li><b>Naam         : {$v->Naam}</b></li>
                <li><b>Status       : {$v->Status}</b></li>
                <li><b>Aanbieder    : {$v->VerstrekkerNaam}</b></li>
                <li><b>Bedrag       : {$v->Bedrag}</b></li>
                <li><b>Begindatum   : {$v->Begindatum}</b></li>

            </ul>
      </td>
</tr>

Answer by Starx

You can try this

$d = "2012-07-02T00:00:00";
echo $newDate = date("d-m-Y",strtotime($d));

Demo

In your code you may apply it as

foreach($array as $k=>$v){
 print "
 <tr>
      <td>
            <ul>
                <li><b>Naam         : {$v->Naam}</b></li>
                <li><b>Status       : {$v->Status}</b></li>
                <li><b>Aanbieder    : {$v->VerstrekkerNaam}</b></li>
                <li><b>Bedrag       : {$v->Bedrag}</b></li>
                <li><b>Begindatum   : {" . date("d-m-Y",strtotime($v->Begindatum)) ."}</b></li>
            </ul>
      </td>
</tr>
February 25, 2013

get all weekdays in php

Question by Keydi

I am thingking if how to get all the date of weekdays between a given date

example: I have a date given 2013-01-01 and 2013-20-01

It must return all date of weekdays like 2013-01-01

how could this be done using php
thankz

Answer by Starx

Look into DatePeriod Class, this is available from PHP 5.3.

Here is an example from the site

$begin = new DateTime( '2012-08-01' );
$end = new DateTime( '2012-08-31' );
$end = $end->modify( '+1 day' );

$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);

foreach($daterange as $date){

       // You can manipulate the date here
    echo $date->format("Ymd") . "<br>";
}
April 23, 2012

Converting php4 date() to php5 date_format()

Question by j-man86

I have the following code:

$date = mktime(12, 0, 0, $month, 1, $year); // 1st day of month as unix stamp
for( $day = 1; $day <= date("t", $date); $day++ ) {
     //...
}

When executed it produces the following notice:

Notice: A non well formed numeric value encountered in
/home2/wordprh4/public_html/contenido/themes/bam/events/table-mini.php
on line 53

I would like to convert date(); using php5 date_format() but I’m having some issues…

What’s the correct way to do this?


FYI line 53 is

for( $day = 1; $day <= date("t", $date); $day++ ) {

Answer by Starx

I dont see a need to do this, but You can use date_format() like this

$date = date_create('2012-02-01'); //First you have to create the date
echo date_format($date, 'Y-m-d H:i:s'); //Next simply pass the needed format

PHP redirect on exact date

Question by user990175

I’m using this code to redirect based on the hour of the day, and the day of the week.

Here it is ..

<?php

$hour = date('G');
$minute = date('i');
$day = date('w');
$m = $hour * 60 + $minute; // Minutes since midnight.

if (
  $day == 0    // Sunday...
  && $m >= 615 // ... after 10:15…
  && $m <= 700 // ... but before 11:40…
) {
  header("Location: open.php");
}
else
if (
  $day == 3     // Wednesday...
  && $m >= 1125 // ... after 18:45…
  && $m <= 1235 // ... but before 20:35…
) {
  header("Location: open.php");
}

?>

I was wondering if there was a way to redirect to a page based on an exact date in the future like April 25th or November 1st.

Thanks .

Answer by Dan Lee

This is a simple approach, which does not take account the year date:

// 25th april:
if (date('d') == '25' && date('m') == '4') {
  header('Location: open.php');
}
// 1st nov:
if (date('d') == '1' && date('m') == '11') {
  header('Location: open.php');
}

Look at the date() documentation for more exact details.

Answer by Starx

Convert the redirection date into timestamp using strtotime() or date() and you can do it easily

if(strtotime("2012/5/3") <= time()) {
     header("location: toredirect.php");
     exit;
}
April 3, 2012

Date between MySQL and PHP

Question by Chris Hardaker

I have a table with a field of type date within a MySQL database. My user places a date into a field (format dd-mm-yyyy) which I convert into yyyy-mm-dd for insertion into the database. This works fine. I can see the date in there as (for example) 2012-04-04.

My issue is that I then select this record, convert the date to the format I wish to display (dd-mm-yyyy) and get 03-04-2012. I understand why, in that my database is set to UTC, however the user is on Berlin time, therefore 04-04-2012 00:00 in Berlin is 03-04-2012 23:00 UTC.

The issue means that if I then save the displayed date (03-04-2012), the next time I see it, it displays as 02-04-2012 because I saved only the date and therefore the system is assuming a 00:00 time again.

I cannot see a way around this other than setting this as a datetime type rather than a date type, however I would rather not do that as time (for various reasons) is stored in a separate field. Any suggestions?

Answer by h4cky

When you inserting a record you add as datetime current UTC time, after that every user in their profile may want to/or set his timezone.

If you know the timezone of the user u can easy convert the datetime to user locale time. Because you know the differences in hours/minutes between the time.

P.S. You can store the datetime as varchar and save the unix timestamp in this field. Unix timestamp is based on current timezone I think.

UPDATE:
I think that might help

$date = time();
dump(date('d-m-Y H:i:s', $date)); // 03-04-2012 08:43:38

date_default_timezone_set('Europe/London');
dump('London: '. date('d-m-Y H:i:s', $date)); // London: 03-04-2012 11:43:38

date_default_timezone_set('Europe/Berlin');
dump('Berlin: '. date('d-m-Y H:i:s', $date)); // Berlin: 03-04-2012 12:43:38

date_default_timezone_set('Europe/Sofia');
dump('Sofia: '. date('d-m-Y H:i:s', $date)); // Sofia: 03-04-2012 13:43:38

dump function returns '<pre>'. $something .'</pre>';

Answer by Starx

First, make sure both time zones are same. Then, don’t store in datatime format, use integer. Convert the date to timestamps and then store. Like

$time = time(); //get the current time stamp
//Now insert $time

Now, both places are in common ground, You may do as you like. Changing date among different timezone is rather easy.

echo gmdate("M d Y H:i:s", $time);
April 1, 2012

PHP if date equals then

Question by huddds

Hi I’m trying use a datepicker on a field I have. I’m trying to set the date field up so the user can only edit this field if the date value in the database is set to deafault (0000-00-00). If there is a value that’s not equal to default I want to show the date created.

Here’s the code I have attempted:

          if( $post['Date'] = var_dump(checkdate(00, 00, 0000))){ 
          echo "<input type="text" class="datepicker" name="pDate" style="border:#000099; margin:10px;" value="";
          echo $post['Date'];
          echo ""> <input id="start_dt" class="datepicker">";
          }
          if( $post['Date'] != var_dump(checkdate(00, 00, 0000))){ 
          echo "<span>date created: </span>";
          echo $post['Date'];

          }

It’s not working atm so any help or a point in the right direction would be great.
Please also take into account I haven’t added any proper styling so I’m only after help with the functionality.

Many thanks.

Answer by Starx

var_dump() is used for debugging purpose rather than inside conditional expression. Next, using = assigns the values not checks for them. You are assigning the values of var_dump() results to $post['Date'] So change them to ==

You should be trying to to something like this

  if( $post['Date'] == checkdate(00, 00, 0000)){ 
      echo "<input type="text" class="datepicker" name="pDate" style="border:#000099; margin:10px;" value="".$post['Date']"">";
      echo "<input id="start_dt" class="datepicker">";
  } else {
      echo "<span>date created: </span>";
      echo $post['Date'];
  }

Reverse whole date in php

Question by NaeemX2

OK,

i was using following code to reverse a date to use in php yesterday.

<?php
$d=date("F j Y");
$d=explode(" ", $d);
$month=$d[0];
$day=$d[1];
$year=$d[2];
<?php for ($i=10; $i>0; $i--)
{
      $date=$month."-".$day--."-".$year;
      echo $date;
?>

this was working for me till yesterday 31 March Night. but in the morning on april 1 its started printing

April-1-2012

April-0-2012

April–1-2012 April–2-2012

and so on.

this was the bad logic i used to reverse a date. i realized it soon.
i want this like following.

April-1-2012

March-31-2012

March-30-2012

March-29-2012

and so on

so how this could be possible ?

Thanks in advance.


Well, this also a logic that work perfect for me i made after post of question. but i am really thankful for all answers. that also making me many things clear.

<?php
$d=date("F j Y");
 for ($i=0; $i>-10; $i--)
 {
$date="<br>".date('F-j-Y', strtotime("+$i days"));
echo $date;
}
?>

Answer by Starx

This is probably the quickest way to do it

for($i=1; $i <= 10; $i++) {
    echo date("F j Y", time()-($i*24*60*60)); //Instead of 24*60*60 write 86400 to increase slight performance
}

Demo

March 14, 2012

php mysql group by date with yyyy-mm-dd format

Question by porfuse

I had a mysql table called events with the fields: id, date, and name.
The date field has the format yyyy-mm-dd hh::mm:ss edit: meaning it is in datetime format

I want to group the events by day, and I wasn’t sure how to approach this- is there a way to select only the month and day from the field? or should i use PHP after I select all the “events”

my end goal is to have something like this:

March 10th: 
  event1, 
  event2
March 11th: 
  event4, 
  event5

I found MySQL select using datetime, group by date only but I’m not sure how to implement it:

SELECT DATE_FORMAT(date, '%H%i'), DATE_FORMAT(date, '%M %D'), name FROM events ORDER BY date

Thanks!

EDIT:

ended up using this:

$sql = “select team1, team2, DATE_FORMAT(date,’%Y-%m-%d’) as created_day FROM games WHERE attack = ‘1’ GROUP BY created_day”;
$result = mysql_query($sql);
$curDate = “”;

    while (list($team1, $team2, $date) = mysql_fetch_row($result))
    {
      if ($date != $curDate)
      {
        echo "$date --------n";
        $curDate = $date;
      }

      echo "game data: $team1 $team2";
    }

Answer by Kharaone

You should indeed use php to get this done. But since most of current system sepate logic from display, I’d use only one pass and not (NUMBER OF DAYS + 1) SELECTs, and prepare an array that I can reuse later for my display.

$query = "SELECT DATE_FORMAT(date, '%M %D') as d, name FROM yourtable ORDER BY date";
$foo=array();
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
    //some logic to test if it's safe to add the name
    $foo[$row['d']][]=$row['name'];

}

And then when i’d need it (through a template or your “view”)

foreach($foo as $date => $events) {
    echo $date . ":nt";          
    echo implode(",nt", $events);
    echo "n";
}

so it fits the format you set to yourself.

Hope that helped

Answer by Starx

If you use group by you will not get one row out of it. So the way you want is not possible through Group By AFAIK.

$query = "SELECT distinct(DATE_FORMAT(date, '%M %D')) as d FROM yourtable";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
   echo $row['d']
   $sql = "SELECT * FROM yourtable WHERE DATE_FORMAT(date, '%M %D')='$row[d]'";
   $rs = mysql_query($query);
   while($r = mysql_fetch_assoc($rs)) {   
      echo "event";
   }
}
...

Please fill the form - I will response as fast as I can!