Home > OS >  Convert Text time into DateTime variable c#
Convert Text time into DateTime variable c#

Time:09-22

I would like to add '2 weeks' to an existing DateTime variable?

If I have the following date: 2000/01/01 and add two weeks, I'd like to have 2000/01/14.

CodePudding user response:

As I understand it, you are given an input of "2 weeks" and you need to convert it into DateTime. Assuming there is a limit to what inputs you can take, you might just week to manually parse it and convert a "week" to 7 days (and multiply by 2).

Microsoft has a project that is designed to understand written text so you might try it if there are too many input possibilities.

https://github.com/Microsoft/Recognizers-Text/tree/master/.NET

CodePudding user response:

You can use this class to convert string to Datetime:

using System;

namespace ConsoleApp
{
    public class ConvertDate
    {
        public DateTime ToDate(string dateStr) {
            if (DateTime.TryParse(dateStr, out var date))
                return date;
            else
                return DateTime.MinValue;
        }
    }
}

And Test your work

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ConsoleApp.Tests
{
    [TestClass()]
    public class ConvertDateTests
    {
        [TestMethod()]
        public void ToDateTest()
        {
            var getdate = new ConvertDate().ToDate("2000/01/01");
            var add2Weeks = getdate.AddDays(14-1);//-1 beacuse the first day is 2000/01/01
            var expectation = new ConvertDate().ToDate("2000/01/14");
            Assert.AreEqual(add2Weeks, expectation);
        }
    }
}
  • Related