Files
resume/lib/services/tools.dart

109 lines
3.3 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
class Tools {
Tools._();
/// Builds a formatted time string from two date strings in the format 'YYYY-MM'.
///
/// Returns a string in the format 'Month Year - Month Year' using localized month names.
/// Returns an empty string if either input is empty or invalid.
///
/// Parameters:
/// - [startDate]: String in 'YYYY-MM' format (e.g., '2024-03')
/// - [endDate]: String in 'YYYY-MM' format (e.g., '2024-12')
/// - [context]: BuildContext for accessing localizations
///
/// Example:
/// ```dart
/// final timeString = buildTimeString('2024-03', '2024-12', context);
/// // Returns "March 2024 - December 2024" (or localized equivalent)
/// ```
static String buildTimeString(
String startDate, String endDate, BuildContext context) {
// Check for empty or null inputs
if (startDate.isEmpty || endDate.isEmpty) {
return '';
}
try {
// Validate date format
if (!startDate.contains(RegExp(r'^\d{4}-\d{2}$')) ||
!endDate.contains(RegExp(r'^\d{4}-\d{2}$'))) {
return '';
}
// Parse dates with validation
final firstDate = DateTime.tryParse('$startDate-01');
final secondDate = DateTime.tryParse('$endDate-01');
// Check if parsing was successful
if (firstDate == null || secondDate == null) {
return '';
}
// Build the formatted string
return '${getLocalizedMonth(context, firstDate.month)} ${firstDate.year} - '
'${getLocalizedMonth(context, secondDate.month)} ${secondDate.year}';
} catch (e) {
// Handle any unexpected errors
debugPrint('Error building time string: $e');
return '';
}
}
/// Returns the localized month name as a [String] based on the provided month number.
///
/// The [context] is used to access the app's localizations.
/// The [monthNumber] must be between 1 and 12, where 1 represents January
/// and 12 represents December.
///
/// Throws an [ArgumentError] if the month number is not between 1 and 12.
///
/// Example:
/// ```dart
/// final monthName = getLocalizedMonth(context, 3); // Returns "March" or "März"
/// ```
static String getLocalizedMonth(BuildContext context, int monthNumber) {
final localizations = AppLocalizations.of(context)!;
switch (monthNumber) {
case 1:
return localizations.january;
case 2:
return localizations.february;
case 3:
return localizations.march;
case 4:
return localizations.april;
case 5:
return localizations.may;
case 6:
return localizations.june;
case 7:
return localizations.july;
case 8:
return localizations.august;
case 9:
return localizations.september;
case 10:
return localizations.october;
case 11:
return localizations.november;
case 12:
return localizations.december;
default:
throw ArgumentError('Month number must be between 1 and 12');
}
}
static String getLocaleFromPath(String path) {
if (path.startsWith('/de')) {
return 'de';
} else if (path.startsWith('/en')) {
return 'en';
}
return 'de'; // Default fallback
}
}