2012-06-27

C# 문자열의 yy, mm, dd를 지정한 날짜데이터의 숫자로 변환하기

파일을 날짜별로 생성해야 해서 만들었다.

public string ConvertDateInString(string filenameFormat, DateTime targetdate)

string filenameFormat에 "yymmdd_파일이름_yymmdd-1.xlsx"를  넘겨주면,
targetdate의 년월일의 숫자데이터로 변경한다.
return string은 변경된 이름이다.
(소문자 yy, mm, dd 또는 yyyy만 인식한다.)

 
/// 지정한 날짜 데이터의 숫자로 yy, mm ,dd 또는 yyyy를 replace 함.
/// 
using System;

namespace automating_system_report
{
    class DateStringConverter
    {
        #region global var
        FindNumberInString fn = new FindNumberInString(); // source에서 숫자 부분을 검출,  +나 - 기호의 뒤에 숫자가 위치하면, 날짜 데이터에 가감하기 위해 선언
        #endregion global var

        /// 
        /// filenameFormat을 yy, dd, mm의 해당 문자열을 targetdate의 날짜 데이터로 바꿈
        /// 파라미터 설명은 2012년 6월 26일을 예로 함.
        /// 
        /// 
ex) yyyymmdd점검일지yy-mm-dd-1.xlsx
        /// 
ex)날짜 데이터(2012-06-26)
        /// ex) 20120626점검일지12-06-25.xlsx
        public string ConvertDateInString(string filenameFormat, DateTime targetdate)
        {
            fn.FindNumber(filenameFormat);
            DateTime convertedDate=targetdate;

            filenameFormat = RecursiveReplaceDate(filenameFormat, "dd", ref targetdate); //filenameFormat의 dd부분을 days로 변경
            filenameFormat = RecursiveReplaceDate(filenameFormat, "mm", ref targetdate); //filenameFormat의 mm부분을 months로 변경
            if(filenameFormat.LastIndexOf("yyyy")>-1)
                filenameFormat = RecursiveReplaceDate(filenameFormat, "yyyy", ref targetdate); //filenameFormat의 yyyy부분을 years로 변경
            else if(filenameFormat.LastIndexOf("yy")>-1)
                filenameFormat = RecursiveReplaceDate(filenameFormat, "yy", ref targetdate); //filenameFormat의 yy부분을 years로 변경
            
            if ((filenameFormat.IndexOf("yy")>-1) ||(filenameFormat.IndexOf("mm")>-1) ||(filenameFormat.IndexOf("dd")>-1) )
            {
                filenameFormat=ConvertDateInString(filenameFormat,targetdate);
            }
            return filenameFormat;
        }
        public string RecursiveReplaceDate(string source, string repStr, ref DateTime convertedDate)
        {
            int whereIsrepStr=-1;  // repStr이 있는 위치를 저장할 변수
            int adjustLocPredication=-1; // repStr뒤에 +나 -로 조정할 기호가 있을 위치를 비교하기 위한 변수
            int adjustVal=0;  // +나 -로 조정할 기호가 있다면 조정할 수치
            int adjustLength=0; // +나 - 기호부터 ~ 수치까지 길이
            string dating=""; //년월일에 변경할 숫자 문자.
            string prestr; //숫자로 변경할 날짜부분의 앞
            string poststr;//숫자로 변경할 날짜부분의 뒤
            DateTime convertedDate;// targetdate에서 +,-로 변경한 날짜데이터.
            try
            {
                whereIsrepStr = source.LastIndexOf(repStr); //뒤에서부터 repStr을 검색, 위치를 기억
            }
            catch { whereIsrepStr = -1; } //repStr을 source문자열에서 못찾을 경우

            if (whereIsrepStr > -1)// 바꿀 대상인 repStr이 문자열에 있으면, 숫자로 변환하기 위해 아래를 수행
            {
                adjustLocPredication = whereIsrepStr + repStr.Length; //adjustLocPredication는 문자열에서 repStr위치한 다음 칸

                // 먼저 repStr뒤에 +나 - 기호의 조정자가 있는지 검색
                foreach (FindNumberInString.NumberInStringSTRUCT n in fn.ListNumber) //filenameFormat의 숫자의 값과 위치를 담고 있는 ListNumber를 foreach
                {
                    //Trace.WriteLine(n.StartIndex);
                    if (n.StartIndex == adjustLocPredication + 1) //foreach수행한 요소마다 위치가 +, - 기호 뒤에 위치하는지 비교
                    {                                             //(+,-기호 위치 바로 뒤에 오는 숫자는 날짜데이터에서 변경할 값으로 인식)
                        adjustVal = Int32.Parse(n.NumberString); //adjustVal은 날짜에서 변경할 값
                        // +기호인지 -기호인지 확인
                        char[] sign = source.ToCharArray();
                        if (sign[adjustLocPredication] == '-')
                        {
                            adjustVal *= (-1); //음수
                            adjustLength=n.Length+1;
                        }
                        else if (sign[adjustLocPredication ] == '+')
                        {
                            adjustLength=n.Length+1;
                        }
                        else { adjustVal = 0; } // + , - 기호가 없으면 날짜에서 변경할 값이 아닌 일반 숫자로 받아들임
                    }
                }
                switch (repStr) //repStr의 종류에 따라 위에서 찾은 adjustVal만큼 조정후, 년월일에 해당하는 문자열을 substring
                {
                            case "dd":
                                convertedDate = targetdate.AddDays(adjustVal);
                                dating = convertedDate.Date.ToString().Substring(8, 2);

                                break;
                            case "mm":
                                convertedDate = targetdate.AddMonths(adjustVal);
                                dating = convertedDate.Date.ToString().Substring(5, 2);

                                break;
                            case "yyyy":
                                convertedDate = targetdate.AddYears(adjustVal);
                                dating=convertedDate.Date.ToString().Substring(0,4);

                                break;
                            case "yy":
                                convertedDate= targetdate.AddYears(adjustVal);
                                dating=convertedDate.Date.ToString().Substring(2,2);
                                break;
                }
                if (dating!="")
                {
                     prestr = source.Substring(0, whereIsrepStr); //변경할 문자열을 제외한 앞부분
                     poststr = source.Substring(whereIsrepStr + repStr.Length + adjustLength);//변경할 문자열을 제외한 뒷부분
                     source = prestr + dating + poststr;//앞부분 + 날짜문자열 + 뒷부분을 다시 source에 저장
                }
                
            }
            return source;
        }
    }
}
//

댓글 없음:

댓글 쓰기