Date Formatting in Vue
December 20, 2024 · AI Conversations
### Using `Intl.DateTimeFormat`
// Assuming you have a date string or object
const formatDate = (date) => {
return new Intl.DateTimeFormat('en-US', {
year: '2-digit',
month: '2-digit',
day: '2-digit',
}).format(new Date(date));
};
// Example usage in Vue
<template>
<div>
<p>Formatted Date: {{ formatDate('2024-12-20') }}</p>
</div>
</template>
<script>
export default {
methods: {
formatDate(date) {
return new Intl.DateTimeFormat('en-US', {
year: '2-digit',
month: '2-digit',
day: '2-digit',
}).format(new Date(date));
},
},
};
</script>
—
### Using `dayjs`
Install the library if it's not already in your project:
yarn add dayjs
Then, in your Vue component:
import dayjs from 'dayjs';
<template>
<div>
<p>Formatted Date: {{ formatDate('2024-12-20') }}</p>
</div>
</template>
<script>
import dayjs from 'dayjs';
export default {
methods: {
formatDate(date) {
return dayjs(date).format('MM/DD/YY');
},
},
};
</script>
—
### Using `date-fns`
Install the library:
yarn add date-fns
Then, in your Vue component:
import { format } from 'date-fns';
<template>
<div>
<p>Formatted Date: {{ formatDate('2024-12-20') }}</p>
</div>
</template>
<script>
import { format } from 'date-fns';
export default {
methods: {
formatDate(date) {
return format(new Date(date), 'MM/dd/yy');
},
},
};
</script>
—
### Tips
1. If you frequently format dates, consider creating a helper file to centralize the logic.
2. Make sure the date format matches the locale expectations.
3. For global usage, you can create a Vue filter or plugin. Let me know if you want to set that up!
### Using Laravel's Carbon for Server-Side Formatting
If you want to format dates server-side in Laravel before sending them to your Vue component, you can use Carbon like this:
use CarbonCarbon;
$formattedDate = Carbon::now()->format('m/d/y');
// or for a specific date
$formattedDate = Carbon::createFromFormat('Y-m-d', '2024-12-20')->format('m/d/y');
You can send this formatted date to your Vue component via your API response:
public function index()
{
$formattedDate = Carbon::now()->format('m/d/y');
return Inertia::render('YourComponent', [
'date' => $formattedDate,
]);
}
### Using Vue.js for Client-Side Formatting
If you want to format dates directly in your Vue.js component, you won't find a default method in Vue.js itself, but you can use the `Intl.DateTimeFormat` method or libraries as previously mentioned.
### Example of Sending Formatted Dates from Laravel
If you send a date string (like `2024-12-20`) from Laravel to Vue and then format it in Vue, you can do something like this:
// Laravel Controller
public function index()
{
$date = '2024-12-20'; // Example date
return Inertia::render('YourComponent', [
'date' => $date,
]);
}
// YourComponent.vue
<template>
<div>
<p>Formatted Date: {{ formatDate(date) }}</p>
</div>
</template>
<script>
export default {
props: {
date: String,
},
methods: {
formatDate(date) {
return new Intl.DateTimeFormat('en-US', {
year: '2-digit',
month: '2-digit',
day: '2-digit',
}).format(new Date(date));
},
},
};
</script>
### Summary
While Laravel provides excellent date handling via Carbon, there are no built-in Vue methods for date formatting. You can handle formatting either server-side with Carbon or client-side with JavaScript. If you frequently need date formatting, consider using a date library like `dayjs` or `date-fns` for convenience and consistency across your application.
### Step 1: Modify the Model
In your `Post` model, you can override the `getCreatedAtAttribute` method to return the `created_at` date in the desired format. Here’s an example that formats the date as `m/d/y`:
use CarbonCarbon;
use IlluminateDatabaseEloquentModel;
class Post extends Model
{
// Other model properties and methods
// Format the created_at attribute
public function getCreatedAtAttribute($value)
{
return Carbon::parse($value)->format('m/d/y');
}
// Optionally, if you want to format updated_at too
public function getUpdatedAtAttribute($value)
{
return Carbon::parse($value)->format('m/d/y');
}
}
### Step 2: Use the Model
Now, when you retrieve the `created_at` attribute from a `Post` instance, it will automatically be formatted as `m/d/y`:
$post = Post::find(1);
echo $post->created_at; // Outputs something like "12/20/24"
### Step 3: Returning Data in API Responses
If you’re returning the post data through an API (like in an Inertia.js response), you can simply include the `created_at` field, and it will be formatted as specified:
public function index()
{
$posts = Post::all();
return Inertia::render('YourComponent', [
'posts' => $posts,
]);
}
### Alternative: Custom Accessor
Alternatively, if you want to avoid overriding the original `created_at` attribute, you can create a custom accessor:
class Post extends Model
{
// Other model properties and methods
public function getFormattedCreatedAtAttribute()
{
return Carbon::parse($this->created_at)->format('m/d/y');
}
}
You can then access it like this:
$post = Post::find(1);
echo $post->formatted_created_at; // Outputs the formatted date
### Summary
By overriding the `getCreatedAtAttribute` method or creating a custom accessor, you can easily change the format of the `created_at` field in your model to suit your needs. This method keeps your code clean and ensures that any access to the `created_at` attribute returns the correctly formatted date.