33import logging
44from typing import Optional
55
6- from app_config import config
7-
8- # Try to import babel, with fallback if not available
9- try :
10- from babel .dates import format_datetime
11- BABEL_AVAILABLE = True
12- except ImportError :
13- BABEL_AVAILABLE = False
14- logging .warning ("Babel library not available. Date formatting will use basic Python formatting." )
15-
16-
17- def _format_date_fallback (date_obj : datetime , language_code : str ) -> str :
18- """
19- Fallback date formatting when babel is not available.
20-
21- Args:
22- date_obj (datetime): The datetime object to format
23- language_code (str): Language code like 'en-US', 'en-IN', etc.
24-
25- Returns:
26- str: Formatted date string
27- """
28- # Normalize the language code
29- normalized_code = language_code .replace ('-' , '_' )
30-
31- # Define basic date formats for different locales
32- locale_date_formats = {
33- 'en_IN' : '%d %B, %Y' , # 29 July, 2025
34- 'en_US' : '%B %d, %Y' , # July 29, 2025
35- 'en_GB' : '%d %B %Y' , # 29 July 2025
36- 'en_AU' : '%d %B %Y' , # 29 July 2025
37- 'en_CA' : '%B %d, %Y' , # July 29, 2025
38- 'es_ES' : '%d de %B de %Y' , # Would need Spanish month names
39- 'fr_FR' : '%d %B %Y' , # Would need French month names
40- 'de_DE' : '%d. %B %Y' , # Would need German month names
41- 'ja_JP' : '%Y年%m月%d日' , # 2025年07月29日
42- 'ko_KR' : '%Y년 %m월 %d일' , # 2025년 07월 29일
43- 'zh_CN' : '%Y年%m月%d日' , # 2025年07月29日
44- }
45-
46- # Get the format for the locale, default to US format
47- date_format = locale_date_formats .get (normalized_code , '%B %d, %Y' )
48-
49- try :
50- return date_obj .strftime (date_format )
51- except Exception as e :
52- logging .warning ("Fallback date formatting failed: %s" , str (e ))
53- return date_obj .strftime ('%Y-%m-%d' ) # ISO format as last resort
54-
55-
566def format_date_for_user (date_str : str , user_locale : Optional [str ] = None ) -> str :
577 """
588 Format date based on user's desktop locale preference.
599
6010 Args:
61- date_str (str): Date in ISO format (YYYY-MM-DD) or datetime object .
11+ date_str (str): Date in ISO format (YYYY-MM-DD).
6212 user_locale (str, optional): User's locale string, e.g., 'en_US', 'en_GB'.
6313
6414 Returns:
6515 str: Formatted date respecting locale or raw date if formatting fails.
6616 """
6717 try :
68- # Get user's browser language from config
69- lang = config .get_user_local_browser_language () # e.g., 'en-US', 'fr-FR', 'de-DE'
70-
71- # Parse the date string if it's a string, otherwise use as-is if it's already a datetime
72- if isinstance (date_str , str ):
73- # Try different date formats
74- date_formats = [
75- "%Y-%m-%d" , # 2025-07-29
76- "%Y-%m-%d" , # 2025-07-29 14:30:00
77- "%Y-%m-%d" , # 2025-07-29T14:30:00
78- "%d/%m/%Y" , # 29/07/2025
79- "%m/%d/%Y" , # 07/29/2025
80- ]
81-
82- parsed_date = None
83- for date_format in date_formats :
84- try :
85- parsed_date = datetime .strptime (date_str , date_format )
86- break
87- except ValueError :
88- continue
89-
90- if parsed_date is None :
91- logging .warning ("Could not parse date string: %s" , date_str )
92- return date_str # Return original string if parsing fails
93-
94- date_to_format = parsed_date
95- else :
96- # Assume it's already a datetime object
97- date_to_format = date_str
98-
99- # Format the date using babel with the user's locale, or fallback to basic formatting
100- if BABEL_AVAILABLE :
101- try :
102- # Babel expects locale in format like 'en_US', not 'en-US'
103- babel_locale = lang .replace ('-' , '_' )
104- formatted_date = format_datetime (date_to_format , locale = babel_locale )
105- except Exception as e :
106- logging .warning ("Babel formatting failed: %s. Using fallback formatting." , str (e ))
107- formatted_date = _format_date_fallback (date_to_format , lang )
108- else :
109- formatted_date = _format_date_fallback (date_to_format , lang )
110-
111- print (
112- f"Formatted date for user ######################### : { formatted_date } using locale: { lang } ,browser lang { config .get_user_local_browser_language ()} , locale: { babel_locale } "
113- )
114- return formatted_date
115-
18+ date_obj = datetime .strptime (date_str , "%Y-%m-%d" )
19+ locale .setlocale (locale .LC_TIME , user_locale or '' )
20+ return date_obj .strftime ("%B %d, %Y" )
11621 except Exception as e :
117- logging .error ("Error formatting date '%s': %s" , date_str , str (e ))
118- # Return the original input if anything goes wrong
119- return str (date_str )
22+ logging .warning (f"Date formatting failed for '{ date_str } ': { e } " )
23+ return date_str
0 commit comments