How to calculate relative time (e.g., "2 hours ago") in C#?
Hello everyone! I'm a beginner C# developer and I've encountered a task: I need to display dates in a "relative time" format — like they do in social networks. Instead of "01.03.2024 14:30" it should show "5 minutes ago", "yesterday", "3 days ago", and so on.\n\nFor example, I have a list of comments with a `DateTime CreatedAt` field. I want to show the user how much time has passed since creation. But the standard `DateTime.ToString()` only outputs the absolute date.\n\nI tried to write a simple function, but it works poorly — it incorrectly handles boundaries (e.g., "yesterday" instead of "1 day ago"), doesn't account for yesterday if less than 24 hours have passed, and generally looks terrible:\n\n```csharp\npublic string GetRelativeTime(DateTime dateTime)\n{\n var span = DateTime.Now - dateTime;\
No answers yet.
Log in to leave an answer
Blogs