0

I have the following problem. The timeformat my database gives me back depends on the server settings. So, if I do this query:

string query = "SELECT d.id, i.name, d.address, d.sensor, d.value, d.made, d.received, s.type, r.name AS room
            FROM info AS i
            RIGHT JOIN data AS d ON i.address = d.address AND i.sensor = d.sensor
            LEFT  JOIN sensor_types AS s ON i.type = s.id
            LEFT  JOIN room AS r ON i.room = r.id
            WHERE i.address = '" + address + "'
            && i.sensor  = '" + sensor  + "'
            && DATE(d.received) BETWEEN '" + start + "' AND '" + end + "'";

On server 1 I get back for today 2013-12-23 2:29:14 and on server 2 I get back 23-12-2013 2:29:14.

In some cases I need the unixtime so I use this function for it, which works fine in case 1 but gives an error in case 2:

public string DateTimeToUnixTime(string text)
{
    DateTime myDate = DateTime.ParseExact(text, "yyyy-MM-dd HH:mm:ss",
                               System.Globalization.CultureInfo.InvariantCulture);
    TimeSpan span = (myDate - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());

    //return the total seconds (which is a UNIX timestamp)
    return ((double)span.TotalSeconds).ToString();

}

What is the best way to fix this?

2 Answers 2

2

If you need to convert datetime to unix time. You can use UNIX_TIMESTAMP() function of MySQL for that.

Try this:

SELECT UNIX_TIMESTAMP(STR_TO_DATE('Dec 23 2013 02:29AM', '%M %d %Y %h:%i%p'))

You can read more here.

Hope that helps! :)

Sign up to request clarification or add additional context in comments.

Comments

2

Not saying it's the best way, but if the only possible formats are those two, you could test for one using DateTime.TryParseExact, and if it fails, assume it's the other format.

DateTime myDate;

if (!DateTime.TryParseExact(text, "yyyy-MM-dd HH:mm:ss",
                           System.Globalization.CultureInfo.InvariantCulture,
                           DateTimeStyles.None, out myDate);
{
    myDate = DateTime.ParseExact(text, "dd-MM-yyyy HH:mm:ss",
                           System.Globalization.CultureInfo.InvariantCulture);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.