Converts a date stored in a MM DD YY format and a time stored in HHMMSS.XXX format to a datetime object. - CSharp System

CSharp examples for System:DateTime Format

Description

Converts a date stored in a MM DD YY format and a time stored in HHMMSS.XXX format to a datetime object.

Demo Code

//NMEA Parser is free software: you can redistribute it and/or modify
using System.Globalization;
using System;//from  w w w  .  ja  v  a  2s.c o m

public class Main{
        /// <summary>
        ///  Converts a date stored in a MMDDYY format and a time stored in HHMMSS.XXX format to a datetime object.
        /// </summary>
        /// <param name="date">The date to be converted, in MMDDYY format.</param>
        /// <param name="time">The time to be converted, in HHMMSS.XXX format.</param>
        /// <returns></returns>
        public static DateTime GetDate(string date, string time)
        {
            if (!IsShortDate(date))
            {
                throw new ArgumentException("Invalid date argument");
            }

            if (!IsTime(time))
            {
                throw new ArgumentException("Invalid time argument");
            }

            int day = Int32.Parse(date.Substring(0, 2));
            int month = Int32.Parse(date.Substring(2, 2));
            int year = 2000 + Int32.Parse(date.Substring(4, 2));
            int hour = Int32.Parse(time.Substring(0, 2));
            int minute = Int32.Parse(time.Substring(2, 2));
            int second = Int32.Parse(time.Substring(4, 2));
            int millisecond = Int32.Parse(time.Substring(7, 3));

            DateTime dateTime = new DateTime(year, month, day, hour, minute, second, millisecond);
            return dateTime;
        }
}

Related Tutorials