I am to read text file where a column of purchase date with format MMDD is available. It is being read and inserted all records successfully. But now i want to insert "system year" with "purchase date" as "dd-MMM-yyyy" into date column of database. Example: If purchase date is "0812" and System Year is '19', then date will be "12-AUG-19". How can i do this ?
As of Oracle, you'd apply a few transformations :
extract
does)to_date
to it, with appropriate format mask ( mmddyyyy
)to_char
to that value, with desired/final format mask ( dd-mon-yyyy
)Something like this:
SQL> select to_char(to_date('0812' || extract(year from sysdate), 'mmddyyyy'), 'dd-mon-yyyy') result from dual;
----
this is what you have, MMDD
RESULT
-----------
12-aug-2019
SQL>
If you are looking for C# code then, you can first Parse
, then create a required DateTime
and, finally, format the DateTime
:
string source = @"0812";
int SystemYear = 19;
// Parsed date, note, that year is DateTime.Now.Year, not required SystemYear
DateTime date = DateTime.ParseExact(source, "MMdd", CultureInfo.InvariantCulture);
date = new DateTime(
CultureInfo.InvariantCulture.Calendar.ToFourDigitYear(SystemYear), // SystemYear
date.Month, // same Month
date.Day); // same Day
// "12-AUG-19"
string result = date.ToString("dd'-'MMM'-'yy", CultureInfo.InvariantCulture).ToUpper();
It depends what is data format in your tables column. If it's type of Date, then showing 12-AUG-19
is just a display issue, and has nothing to do with inserting. If it's varchar column, then you first need to read your date from source fe:
var source = "0812";
source += DateTime.Now.Year;
Console.WriteLine(source);
var date = DateTime.ParseExact(source, "MMddyyyy", System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(date);
So now you have date as DateTime
object, and it depends on your DB structure if you will post it as string
to DB, or as proper Date column.
In Oracle you can insert a date using many different formats, so it would not be necessary to have the format 'DD-mon-YY' to insert the value in a date column. The TO_DATE function uses the current year value by default to complete the format:
SQL> SELECT TO_DATE('0812', 'MMDD')from dual;
TO_DATE('0812','M
-----------------
12/08/19 00:00:00
And this is an example of what I mean:
SQL> CREATE TABLE DATE_SAMPLE ( DATE_VALUE DATE);
Table DATE_SAMPLE creado.
SQL> INSERT INTO DATE_SAMPLE SELECT TO_DATE('0812', 'MMDD')from dual;
1 fila insertadas.
SQL> SELECT TO_CHAR(DATE_VALUE, 'DD-mon-YY') from DATE_SAMPLE;
TO_CHAR(DATE_VALUE,'DD-MON-YY')
---------------------------------------------------------------------------
12-ago-19
You can insert a date specifying the format in the TO_DATE function and read it in the desired format using the TO_CHAR function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.