tags:

views:

120

answers:

2

Is there a way to convert a date to a string in Sqlite? For example I am trying to get the min date in Sqlite:

SELECT MIN(StartDate) AS MinDate FROM TableName

I know in SQL Server I would use the SQL below to accomplish what I am trying to do:

SELECT CONVERT(VARCHAR(10), MIN(StartDate), 101) AS MinDate FROM TableName

Thanks!

+1  A: 

Try this:

SELECT MIN(DATE('your-date-here')) as MinDate FROM TableName

And make sure your-date-here follows a well understood format by SQLite (See the Time String. section in the documentation)

Ricardo Villamil
The result for this is NULL when I run it. Also, "your-date-here" is a DATETIME column from my table. I'm not sure if that makes a difference?
Billy
If it's returning NULL, it's because your argument isn't a valid date. Presumably, you're dates as strings. If so, make sure you use 'YYYY-MM-DD' format.
dan04
SQLite stores dates as strings...as Dan says, you're probably not using a rightly formatted date...
Ricardo Villamil
Here is an example of one of my dates from the database: "2010-06-15 09:50:00 -0400"I'm guessing the "-0400" is what was causing the problem, I removed that and it now works.Thanks!
Billy
+1  A: 

SQLite doesn't have a date type. What CURRENT_TIMESTAMP actually returns is a string in the format YYYY-MM-DD HH:MM:SS. The date/time formatting/calculation functions accept strings in this format, or alternatively, numbers, which are interpreted as Julian dates unless you use the 'unixepoch' modifier.

So, "converting a date to a string" depends on how you're storing your dates:

  • If you're storing them as Julian dates, use DATE(YourDateColumn).
  • If you're storing them as Unix times, use DATE(YourDateColumn, 'unixepoch').
  • If you're storing them as ISO 8601 strings, then, well you don't have to do anything. Unless you want a string in a different format, in which case you should use the STRFTIME function.
  • If you're storing them as some other string format, you really should consider using one of the supported formats so you can use the date/time functions.

In all three date formats, chronological order is the same as lexicographical order, so the MIN function works as expected.

dan04