如何找到两个日期之间的差异

时间:2015-11-27 13:47:26

标签: php

$start = "2015-01-01 10:00:00";

$end = "2015-05-05 12:06:06";


$x = strtotime($start);

$y = strtotime($end);

$z = abs($y - $x);

$days = floor($z / (60 * 60 * 24));
$years = floor($z / (365 * 60 * 60 * 24));

$months = floor(($z - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24));

$days = floor(($z - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24) / (60 * 60 * 24));

$hours = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24) / (60 * 60));

$minuts = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24 - $hours * 60 * 60) / 60);

$seconds = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24 - $hours * 60 * 60 - $minuts * 60));

输出是:

4 month 4 days 1 hour 6 minute 6 seconds

预期输出为:

4 month 4 days 2 hour 6 minute 6 seconds

4 个答案:

答案 0 :(得分:1)

DateTime是在PHP中使用日期的好方法:

$start = "2015-01-01 10:00:00";
$end = "2015-05-05 12:06:06";

$d1 = new DateTime($start);
$d2 = new DateTime($end);

$iv = $d2->diff($d1);

echo $iv->format('%m month, %d days, %h hours, %i minutes, %s seconds');

答案 1 :(得分:0)

您的代码没有任何问题,您可能需要包含您的默认时区,例如我在非洲,所以我总是使用以下行来设置我的时区。

public class AdminNotice extends Activity {

private String[] navMenuTitles;
private TypedArray navMenuIcons;
private EditText editTextName;
SharedPreferences sp;
private String jsonResult;
private ListView listView;
private Button b;
EditText etname, et;
TextView tv;
String myJSON;
private static final String TAG = "MainActivity.java";
private static final String TAG_NAME = "notice";
private static final String TAG_DATE = "ndate";
ProgressBar progressBar;
Date date;
JSONArray peoples = null;

ArrayList<HashMap<String, String>> personList;

ListView list;

public static final String USER_NAME = "USERNAME";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.noticelist);
    progressBar = (ProgressBar) findViewById(R.id.progressbar);


    //SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
    // String session_id= myprefs.getString("session_id", null);


    //TextView textView = (TextView) findViewById(R.id.fname);

    //textView.setText("Welcome "+session_id);





    navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

    navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
    // load icons from
    // strings.xml


    list = (ListView) findViewById(R.id.listView);
    personList = new ArrayList<HashMap<String,String>>();

    getData();




}



//send messages stop

//get json data start
protected void showList(){
    try {
        JSONArray peoples = new JSONArray(myJSON);


        for(int i=0;i<peoples.length();i++){
            JSONObject c = peoples.getJSONObject(i);
            String name=null, date=null;

            /*if(c==null){
                ProgressDialog progress = new ProgressDialog(this);
                progress.setTitle("Loading");
                progress.setMessage("Wait while loading...");
                progress.show();
            }*/



            if(c.has("notice"))
            if(c.has("ndate"))




            progressBar.setVisibility(View.GONE);
            name = c.getString("notice");
            date = c.getString("ndate");


            list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                        long arg3)  {
                    HashMap<String, Object> data = (HashMap<String, Object>) arg0.getItemAtPosition(arg2);
                    Intent intent = new  Intent(getApplicationContext(), SingleMessage.class);
                    intent.putExtra("KEY", data);

                    startActivity(intent);
                }

            });


            HashMap<String,String> persons = new HashMap<String,String>();


            persons.put(TAG_NAME,name);
            persons.put(TAG_DATE,date);
            personList.add(persons);
        }



        ListAdapter adapter = new SimpleAdapter(
                AdminNotice.this, personList, R.layout.list_item1,
                new String[]{TAG_NAME,TAG_DATE},
                new int[]{R.id.name, R.id.date}
        );

        list.setAdapter(adapter);

       /* list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView parent, View view, int position, long id) {


                Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();

            }

        });*/





    } catch (JSONException e) {
        Log.i("tagconvertstr", "["+myJSON+"]");
    }
}





public void getData(){
    class GetDataJSON extends AsyncTask<String, Void, String>{


        @Override
        protected String doInBackground(String... params) {

            SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
            String session_id= myprefs.getString("session_id", null);

            InputStream inputStream = null;
            String result = null;
            try {

                String postReceiverUrl = "http://.php";

                // HttpClient
                HttpClient httpClient = new DefaultHttpClient();

                // post header
                HttpPost httpPost = new HttpPost(postReceiverUrl);

                // add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("username", session_id));

                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpClient.execute(httpPost);
                HttpEntity resEntity = response.getEntity();

                inputStream = resEntity.getContent();
                // json is UTF-8 by default
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();

                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                result = sb.toString();
            } catch (Exception e) {
                Log.i("tagconvertstr", "["+result+"]");
                System.out.println(e);
            }
            finally {
                try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result){
            myJSON = result;
            showList();
        }
    }
    GetDataJSON g = new GetDataJSON();
    g.execute();
}
//get json data stop

您只需要确定您的区域是什么,然后将其分配给方法date_default_timezone_set('Africa/Harare');

答案 2 :(得分:0)

$start_date = new DateTime('2007-09-01 04:10:58');
$since_start = $start_date->diff(new DateTime('2012-09-11 10:25:00'));
echo $since_start->days.' days total<br>';
echo $since_start->y.' years<br>';
echo $since_start->m.' months<br>';
echo $since_start->d.' days<br>';
echo $since_start->h.' hours<br>';
echo $since_start->i.' minutes<br>';
echo $since_start->s.' seconds<br>';

答案 3 :(得分:0)

使用以下代码

$start = date_create('2015-01-01 10:00:00');
$end = date_create('2015-05-05 12:06:06');
$diffObj = date_diff($start, $end);
//accesing days
$days = $diffObj->d;
//accesing months
$months = $diffObj->m;
//accesing years
$years = $diffObj->y;
//accesing hours
$hours=$diffObj->h;
//accesing minutes
$minutes=$diffObj->i;
//accesing seconds
$seconds=$diffObj->s;
echo '<center>';
echo '' . $days . ' day(s), ' . $months . ' month(s), ' . $years . 'year(s), '.$hours.' hour(s),'.$minutes.' minute(s), '.$seconds.' second(s) </b>';
echo '</center>';