2

I am tired to calculate date with start & end date in my Laravel & Vue js project? I have also installed moment js. Code as below,

{{item.start_date | MyDate}} {{item.end_date | MyDate}} {{Here will be calculate between above dates}}

Please help me.

Aminul
  • 67
  • 9

2 Answers2

4

You can create new method with this logic:

methods: {
    parseDate (start, end) {
        return moment(start, 'YYYY.MM.DD HH:mm').diff(moment(end, 'YYYY.MM.DD HH:mm'), "days")
    }
}

And in your template you can simply do that: {{ parseDate(item.start_date, item.end_date) }}

I think is that what you need. Here you can check some examples of using diff in moment.

Good luck!

mare96
  • 3,749
  • 1
  • 16
  • 28
1

If you are getting the data from Laravel you can use Carbon to calculate the difference like this:

$start_date = Carbon::parse($item->start_date);
$end_date = Carbon::parse($item->end_date);

$diff_in_hours = $end_date->diffInHours($start_date);
$diff_in_days = $end_date->diffInDays($start_date)
$diff_in_minutes = $end_date->diffInMinutes($start_date);
$diff_in_seconds = $end_date->diffInSeconds($start_date);

So if you are getting the data from a query you can map the query like this:

$schedules = DB::table('schedules')
                 ->get()
                 ->map(function($item){
                     $start_date = Carbon::parse($item->start_date);
                     $end_date = Carbon::parse($item->end_date);
                     $item->diff = $end_date->diffInMinutes($start_date);

                    return $item;
                 });

The same for models

Schedule::where('status',1)->get()
                 ->map(function($item){
                     $start_date = Carbon::parse($item->start_date);
                     $end_date = Carbon::parse($item->end_date);
                     $item->diff = $end_date->diffInMinutes($start_date);

                    return $item;
                 });
Itamar Garcia
  • 882
  • 10
  • 17