Skip to content

Instantly share code, notes, and snippets.

@matifdeveloper
Last active October 16, 2023 05:42
Show Gist options
  • Save matifdeveloper/f88d176916e1155fa8924ee0f1a05b7e to your computer and use it in GitHub Desktop.
Save matifdeveloper/f88d176916e1155fa8924ee0f1a05b7e to your computer and use it in GitHub Desktop.
Format Time (AM - PM)

Format Time (AM - PM)

Created with <3 with dartpad.dev.

void main() {
List<String> timeStrings = [
"1 AM", "2 AM", "3 AM", "4 AM", "5 AM", "6 AM", "7 AM", "8 AM", "9 AM", "10 AM", "11 AM", "12 AM",
"1 PM", "2 PM", "3 PM", "4 PM", "5 PM", "6 PM", "7 PM", "8 PM", "9 PM", "10 PM", "11 PM", "12 PM"
];
int index = 15; // Replace with the index you want to retrieve (0-based)
String specificTime = timeStrings[index];
print(specificTime);
print(formatTime(specificTime));
}
String formatTime(int hour) {
if (hour >= 1 && hour <= 11) {
return '$hour AM';
} else if (hour == 12) {
return '12 PM';
} else if (hour >= 13 && hour <= 23) {
return '${hour - 12} PM';
} else if (hour == 24) {
return '12 AM';
} else {
return 'Invalid hour';
}
}
int? formatTime(String timeString){
int hour;
if (timeString.endsWith("AM")) {
// Remove "AM" and convert to an integer
hour = int.parse(timeString.replaceAll("AM", ""));
return hour;
} else if (timeString.endsWith("PM")) {
// Remove "PM," convert to an integer, and add 12
hour = int.parse(timeString.replaceAll("PM", "")) + 12;
return hour;
} else {
// Handle an invalid time string or other cases
print("Invalid time format");
return null; // or handle the error accordingly
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment