Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

Getting date and time in a trimmed way

I want to insert a date and time into db in a format like this:

"20 May, 2013 at 5:45"

and if I want to show it in format 2 mins ago, just now, or 6 months ago etc., how can i do it.. :)

Can any one suggest me how to do this please,

Thanks in advance.

Upvotes: 0

Views: 80

Answers (2)

Eric Jablow
Eric Jablow

Reputation: 7899

Databases exist to store data and to let you ask and answer questions about them. Applications come and go; data may last forever. So, what sort of questions might you ask? Granted, we don't know the problem domain, so these are just guesses.

How many orders did we fulfill in the last 7 days?

SELECT COUNT(*) "Orders last week" FROM ORDERS
WHERE
     orderDate >= SYSDATE - 7  -- Oracle code

If you've turned the date into a string, you can't do this.

Who has overdue library books? Which ones?

SELECT u,id, u.first_name, u.last_name, b.id, b.book_name
FROM User u
JOIN Book b ON u.id = b.borrower_id
WHERE b.due_date < SYSDATE
AND b.returned = 0    -- Oracle doesn't have "BOOLEANS" yet.

You can do date arithmetic; adding or subtracting a number from a date datum gives the date that many days later or earlier. There are functions that give "the next Tuesday after a date" or "The first of the year." Your storing the date as a string makes all that closed off for you.

Suppose you need to format your date for the French division of your company. Could you do that with your date strings? Leave formatting for your application, not for the database.

This is an example of the importance of the Model-View-Controller architecture. The model, the part that holds the data, should be independent of any particular application so it can work with any application, and a database is certainly part of the model.

I don't know C#, but similar code exists in SQL-Server, which I'm guessing you use.

Upvotes: 1

AgentFire
AgentFire

Reputation: 9790

Though its completely wrong to store date/date time data as string, you could use the ToString overload to specify the format:

var stringedDate = DateTime.Now.ToString("dd MM',' yyyy 'at' H':'mm");

Upvotes: 1

Related Questions