计算laravel中两个月到一年之间的年数和月份

时间:2018-12-14 11:03:48

标签: php laravel

我想计算两个月和一年之间的差额。我用于计算月份和年份的输入是

$fromYear = 2016;
$fromMonth = 3;
$toYear = 2018;
$toMonth = 9;

我想要一个 2年6个月 2.5年的输出。我正在使用laravel开发我的应用程序。我想通过 carbon 或默认的 php 功能实现这一目标。请帮助我。

3 个答案:

答案 0 :(得分:3)

设置2个碳素实例

$year = 2000; $month = 4; $day = 19
$hour = 20; $minute = 30; $second = 15; $tz = 'Europe/Madrid';
$date = Carbon::createFromDate($year, $month, $day, $tz);
$date->diffForHumans($secondDate);

答案 1 :(得分:1)

这应该有帮助-

$fromYear = 2016;
$fromMonth = 3;
$toYear = 2018;
$toMonth = 9;

$datetime1 = date_create($fromYear . '-' . $fromMonth . '-01');// Concatenate & consider date starts from 1st
$datetime2 = date_create($toYear . '-' . $toMonth . '-01');

$interval = date_diff($datetime1, $datetime2);

var_dump($interval->y . ' years, ' . $interval->m . ' months');

Code

O / P

string(17) "2 years, 6 months"

如果需要,需要添加适当的检查。

答案 2 :(得分:0)

您还可以尝试使用Carbon,它也可以帮助您进行日期验证。

class ApiUtils {

    private ApiUtils() {}



    static APIService getAPIService(String ipCASSA) {

        String BASE_URL = "http://"+ipCASSA+"/web/";

        final OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .writeTimeout(10000, TimeUnit.MILLISECONDS)
                .readTimeout(10000, TimeUnit.MILLISECONDS)
                .retryOnConnectionFailure(false)
                .build();


        return RetrofitClient.getClient(BASE_URL,okHttpClient).create(APIService.class);
    }
}

public interface APIService {

    @POST("CART=PTERM")
    Call<Void> savePost(@Body RequestBody text);

}

class RetrofitClient {

    private static Retrofit retrofit = null;


    static Retrofit getClient(String baseUrl, OkHttpClient okHttpClient) {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}