Hi guys.

I have a date in format "2015-04-04 10:50" (yyyy-MM-dd hh:mm)

I'm having a tough time finding a way to alter this date if a condition is met.
The condition is not the problem, I can get a true of false but the conversion is proving difficult to fathom for me as I've never worked with dates really.

Here is example code.

string d1 = "2015-04-04 00:06";
ConvertDate(d1);

static void ConvertDate(string s)
        {
            if (Convert.ToInt32(s.Substring(11, 2)) < 5) /*00*/
            {
                // Roll the date back by 1 day
            }

        }

If the hour is less than 05 then the date should be rolled back 1 day.
Hope I've explained well enough.
Love to hear any suggestions.

Thanks for reading my post.

(edit)

It would be quite simple if I just had to subtract 1 from the day, except if the day is "01" (I'll probably make that a condition) then It becomes more complicated.

I suppose I'm hoping this has been dealt with before.

Edited 1 Year Ago by Suzie999

Hi Suzie

Does this help?

using System;

namespace DaniWebDates
{
    class Program
    {
        static void Main(string[] args)
        {
            string d1 = "2015-04-04 00:06";

            Console.WriteLine(ConvertDate(d1));

            Console.ReadKey();

        }

        static DateTime ConvertDate(string s)
        {
            return Convert.ToInt32(s.Substring(11, 2)) < 5 ? DateTime.Parse(s).AddDays(-1) : DateTime.Parse(s);
        }
    }
}

Hi DaveAmour, thanks for taking the time to reply.

I tried something simiar.

static void ConvertDate(string s)
        {
            if (Convert.ToInt32(s.Substring(11, 2)) < 5)
            {
                DateTime d = Convert.ToDateTime (s);
                Console.WriteLine(d.ToString());
            }

        }

Both give same incorrect result.

"04/04/2015 00:06:00"

Anyway, you got me on the right track.

static void ConvertDate(string s)
        {
            if (Convert.ToInt32(s.Substring(11, 2)) < 5)
            {
                DateTime d = Convert.ToDateTime (s).AddDays(-1);
                Console.WriteLine(d.ToString("yyyy-MM-dd"));
            }

        }

Thank you very much.

(edit)

Well, in fact I never specified that the output format should be the same as the input format, so you pretty much solved my issue.

Thanks again.

Edited 1 Year Ago by Suzie999

This question has already been answered. Start a new discussion instead.