rameez khan
rameez khan

Reputation: 359

Flutter convert date time to separate date and time with am pm

I am getting date in string like this 2023-01-25T00:37:00.000Z

I try to parse like this DateFormat("dd-MM-y").parse(data.matchScheduleDateTime) but its showing wrong date and time.

If I try like this dateFormat.parse("2023-01-25T00:37:00.000Z") its showing format exception

Upvotes: 0

Views: 1460

Answers (3)

Daniel
Daniel

Reputation: 11

import 'package:intl/intl.dart';

String dateTimeString = "data.matchScheduleDateTime";

// Parse the date time string using the "dd-MM-y" format
var dateTime = DateFormat("dd-MM-y").parse(dateTimeString);

// Format the date part using the "dd-MM-y" format
var dateFormat = DateFormat("dd-MM-y").format(dateTime);

// Format the time part using the "jm" format (j for 12-hour format and m for minutes)
var timeFormat = DateFormat("jm").format(dateTime);

// Format the am/pm part
var amPmFormat = DateFormat("a").format(dateTime);

print("Date: $dateFormat Time: $timeFormat $amPmFormat");

Upvotes: 0

eamirho3ein
eamirho3ein

Reputation: 17910

You can use DateFormat like this:

var date = '2023-01-25T00:37:00.000Z';
var parsedDate = DateFormat('yyyy-MM-ddTHH:mm:ss').parse(date);

var finalDate = DateFormat("MMM dd").format(parsedDate);
var finalTime = DateFormat.jm().format(parsedDate);
var allDate = DateFormat("MMM dd hh:mm a").format(parsedDate);

print("finalDate = $finalDate"); // Jan 25
print("finalTime = $finalTime"); // 12:37 AM
print("allDate = $allDate"); // Jan 25 12:37 AM

Upvotes: 1

CopsOnRoad
CopsOnRoad

Reputation: 267724

You need to parse it using DateTime and convert it using DateFormat:

var oldDate = DateTime.parse('2023-01-25T00:37:00.000Z');
var newDate = DateFormat('MM/dd/yyyy hh:mm a').format(oldDate);
print(newDate); // 01/25/2023 12:37 AM

Upvotes: 2

Related Questions