Convert VARCHAR to date - don't know format in advance
Hi,
If I want to convert varchar to date, but I don't kniow the format of the varchar in advance. For example, it may be '20-MAY-99', '2009-01-10 10:01:00', but it is not known in advance. How can I convert it to date?
Many thanks
You'll have to define a hierarchy of date formats to try. There are some strings that map to many different valid dates depending on the format. The string '01/02/03' might translate to January 2, 2003, January 2, 1903, February 1, 2003, February 1, 1903, February 3, 2001, February 3, 1901, etc.
Assuming you define a hierarchy of formats, you can write a function that tries each format in turn, i.e.
CREATE FUNCTION my_to_date( p_string IN VARCHAR2 )
RETURN DATE
IS
l_date_variable DATE;
BEGIN
l_date_variable := to_date( p_string, <<format 1>> );
return l_date_variable;
EXCEPTION
WHEN OTHERS THEN
BEGIN
l_date_variable := to_date( p_string, <<format 2>> );
return l_date_variable;
EXCEPTION
WHEN OTHERS THEN
END;You'll need to define the N date formats to try and the order in which to try them.
Justin
Similar Messages
-
How to convert varchar to date datatype while insert or update in table
Hai All
I need to convert to varchar to date.
I have two Tables T1,T2
T1 Structure
Code varchar
Time varchar
Date varchar
T2 Structure
Empname var
Empcode var
Intime date
Outtime date
Intrin date
Introut date
Att_date
Now i need to move Time form T1 to T2 Intime,outtime,intrin,introut according some condition
So now i need to convert Varchar to Date while insert or update
I have tried something
Insert into T1 (code,intime,att_date)values
(code,To_date(Date||time,'dd-mon-yyyy hh24mi'),att_date);
OR While update
Update T2 set Outtime=To_date(Date||time,'dd-mon-yyyy hh24mi') where...
I got an error Ora-01861
Regards
Srikkanth.MYou didn't show any example of your date or time values, butyou might need to add a space between them, like
To_date(Date || ' ' || time,'dd-mon-yyyy hh24mi') -
Hi
im trying to convert varchar to date.
So, i used To_date ( cilumn, 'DD-MM-YYYY') , Since i have to order the out put in Decending Order i used the same convertion function with Order by clause.
The problem is ... the out put is not ordered,
<sql>
select date_created
from
select distinct
to_date(created_date,'DD-MM-YYYY') as date_created
from schedule_backup
order by date_created desc
<sql>
out put is
=================
DATE_CREA
26-NOV-09
23-NOV-09
19-NOV-09
16-NOV-09
11-NOV-09
04-NOV-09
30-OCT-09
11-SEP-09
04-MAR-10
01-MAR-10
25-FEB-10
DATE_CREA
22-FEB-10
17-FEB-10
15-FEB-10
11-FEB-10
09-FEB-10
03-FEB-10
27-JAN-10
20-JAN-10
15-JAN-10
04-JAN-10
thanks
rajHi, Raj,
When you store dates in a VARCHAR2 column, you're asking for touble, so it seems that everything is working according to plan.
Even aside from that, your query works perfectly for me.
In the output you posted, the order is correct within each year, and you're only showing 2 digits of the year. Are you sure the centuries are right in the schedule_backup table? Perhaps everything that was supposed to be '2010' got enetereed as '1910' or '0010'.
Post some sample data (CREATE TABLE and INSERT statements) that gets the wrong results with your query.
For example:
CREATE TABLE schedule_backup
( created_date VARCHAR2 (10)
INSERT INTO schedule_backup (created_date) VALUES ('11-11-2009');
INSERT INTO schedule_backup (created_date) VALUES ('04-11-2009');
INSERT INTO schedule_backup (created_date) VALUES ('30-10-2009');
INSERT INTO schedule_backup (created_date) VALUES ('11-09-2009');
INSERT INTO schedule_backup (created_date) VALUES ('04-03-2010');
COMMIT; -
HowTO: convert Image- byte[] when don't know image format?
I have byte[] field in my DB. Images have been stored there.
Images can be jpg/gif/png.
My task is to scale them and save back (to another field)
I have such code:
I know, that getScaledInstance is bad, but please, don't pay attention. This operation +(massive image resizing will be performed once a year at night)+
public class ImageResizer {
private static byte[] resizeImage(byte[] sourceImg, int newWidth){
byte[] result = null;
Image resizedImage = null; //output image
ImageIcon imageIcon = new ImageIcon(sourceImg); //source image
Image imageSource = imageIcon.getImage();
int imageSourceWidth = imageSource.getWidth(null);
int imageSourceHeight = imageSource.getHeight(null);
if(imageSourceWidth > newWidth){
float scaleFactor = newWidth/imageSourceWidth;
int newHeight = Math.round(imageSourceHeight*scaleFactor);
resizedImage = imageSource.getScaledInstance(newWidth, newHeight,Image.SCALE_SMOOTH);
Image temp = new ImageIcon(resizedImage).getImage();// This code ensures that all the pixels in the image are loaded.
// Create the buffered image.
BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null),BufferedImage.TYPE_INT_RGB);
/**And what next?*/
}else{
result = sourceImg;
return result;
public static byte[] scaleToSmall(byte[] sourceImg){
return resizeImage(sourceImg, 42);
public static byte[] scaleToBig(byte[] sourceImg){
return resizeImage(sourceImg, 150);
public static byte[] serializeObjectToBytearray(Object o) {
byte[] array;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
array = baos.toByteArray();
catch (IOException ioe) {
ioe.printStackTrace();
return null;
return array;
}On this forum I've found many solutions, but approximately all of them suppose that I know file format (PixelGrabber, ImageIO, e.t.c). But I don't know it. I know, that it can be jpeg/gif/png.
What can I do?
I've found that simple serialization can help me (+public static byte[] serializeObjectToBytearray(Object o)+), but seems like it doesn't work.
Edited by: Holod on 01.11.2008 10:18Here I came up with one possible solution using some more functionality of ImageIO.
public class ImageResizer {
private static byte[] resizeImage(byte[] sourceBytes, int newWidth) throws Exception {
byte[] scaledBytes;
// ImageIO works with Files or Streams, so convert byte[] to stream
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(sourceBytes);
// Why not just use ImageIO.read(inputStream)? - Because there would be
// no way to know the original image format (I am assuming here that
// you need to write back the image in the same format as the original)
ImageInputStream imageInputStream = ImageIO.createImageInputStream(byteArrayInputStream);
// assuming there is at least one ImageReader able to read the image
ImageReader imageReader = ImageIO.getImageReaders(imageInputStream).next();
// save image format name so we can write it back in the same format
String formatName = imageReader.getFormatName();
imageReader.setInput(imageInputStream);
BufferedImage sourceImage = imageReader.read(0);
int imageSourceWidth = sourceImage.getWidth();
int imageSourceHeight = sourceImage.getHeight();
if (imageSourceWidth > newWidth) {
// be careful with integer divisions ( 500 / 1000 = 0!)
double scaleFactor = (double) newWidth / (double) imageSourceWidth;
int newHeight = (int) Math.round(imageSourceHeight * scaleFactor);
System.out.println("newWidth=" + newWidth + ", newHeight=" + newHeight + ", formatName=" + formatName);
// getScaledInstance provides the best downscaling quality but is
// orders of magnitude slower than the alternatives
// since you're saying performance is not issue, I leave it as is
Image scaledImage = sourceImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
// Unfortunately we need a RenderedImage to use ImageIO.write.
// So the next lines convert whatever type of Image was returned
// by getScaledImage into a BufferedImage.
// Using TYPE_INT_ARGB so potential alpha channels are preserved
BufferedImage scaledBufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = scaledBufferedImage.createGraphics();
g2.drawImage(scaledImage, 0, 0, null);
g2.dispose();
// Now use ImageIO.write to encode the image back into a byte[],
// using the same image format
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(scaledBufferedImage, formatName, byteArrayOutputStream);
scaledBytes = byteArrayOutputStream.toByteArray();
} else {
// if not scaling happened, just return the original byte[]
scaledBytes = sourceBytes;
return scaledBytes;
public static void main(String[] args) throws Exception {
// this is just for my own local testing
// simulate byte[] input from database
BufferedImage image = ImageIO.read(new File("input.jpg"));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(image, "PNG", byteArrayOutputStream);
byte[] sourceBytes = byteArrayOutputStream.toByteArray();
byte[] scaledBytes = resizeImage(sourceBytes, 640);
// write out again to check result
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(scaledBytes);
image = ImageIO.read(byteArrayInputStream);
ImageIO.write(image, "PNG", new File("output.jpg"));
} -
Convert LV waveform data to nCode .dac format?
Does anyone have Vi's or information on how to convert waveform data to nCode .dac format?
Hello dhuff,
Thank you for contacting National Instruments.
I haven't been able to find any VIs built that take LabVIEW data and convert it to nCode, but it can be done. You would need to know details of the way the data is stored in .dac files including endian order, whether it's channel oriented or block oriented, etc. Use the data manipulation VIs in the advanced palette if you need to mainpulate bits, bytes, or words. Then you can use the LabVIEW File I/O VIs for the actual file writing.
Post back if you have any issues using these VIs.
Regards,
Gerardo Garcia
National Instruments
Applications Engineer -
Convert varchar to date in OBIEE-sql server database
Hi we have SQL server database,
and we need to convert varchar to to_date .
In OBIEE we use evaluate,cast etc on Oracle......Not sure about sql server..please helpi am usiing below formula in my reports-answer side:
Cast((case when "Job CV Fact"."Total Cv Sent" is not null then "DATE DIM".Date end)as Date)
below error is coming:
A general error has occurred. [nQSError: 46046] Datetime value 01/01/08 does not match the specified format. (HY000)
cast("DATE DIM".Date as date) the above error comes :) -
Convert varchar(20) date to date that looks like mm/dd/yyyy
Good afternoon,
I am a total novice at SQL and have been tasked to change a varchar(20) date column (shows up as m/dd/yy) to show up as mm/dd/yyyy. I've looked at the previous posts, but being a novice, it's difficult to wade through the non-applicable stuff. The column
that needs to be changed is field2, but I'm not sure how to construct a statement to reflect my objective.
Thank you in advance.The sample uses a table variable. You can program it the same way for a table:
DECLARE @t TABLE (dt VARCHAR(20))
INSERT INTO @t
VALUES ('1/2/12')
,('3/10/10')
,('7/23/9')
,('aa')
,('12/31/99')
,('10/20/00')
,('10/20/01')
SET DATEFORMAT mdy
SELECT dt
,CONVERT(VARCHAR(10), CASE
WHEN isdate(dt) = 0
THEN NULL
ELSE cast(dt AS DATE)
END, 101) AS newDt
FROM @t;/******** TRY_CONVERT() method ************/
SELECT dt, newDt=CONVERT(varchar(10),TRY_CONVERT(date,dt),101) FROM @t;
GO
dt newDt
1/2/12 01/02/2012
3/10/10 03/10/2010
7/23/9 07/23/2009
aa NULL
12/31/99 12/31/1999
10/20/00 10/20/2000
10/20/01 10/20/2001
dt newDt
1/2/12 01/02/2012
3/10/10 03/10/2010
7/23/9 07/23/2009
aa NULL
12/31/99 12/31/1999
10/20/00 10/20/2000
10/20/01 10/20/2001
Starting with SQL Server 2012 you can use TRY_CONVERT().
You can start studying datetime functions here:
http://www.sqlusa.com/bestpractices/datetimeconversion/
Kalman Toth Database & OLAP Architect
T-SQL Scripts at sqlusa.com
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012 -
How to convert varchar to date?
Hello everyone, I'm new to OBIEE and I'm running into a roadblock...
I have a date that is stored in a varchar2 column in the physical table, like so: 20071225
Silly I know, but that's what I'm dealing with.
Anyway, I want to create a logical column in the business model (using the Administration tool) and convert it to a date so that I can do date arithmetic with it, but TO_DATE doesn't seem to be supported.
In Oracle SQL would do this (I'm using XE):
SELECT SYSDATE - TO_DATE('20050101', 'YYYYMMDD') FROM DUAL
Is there any way to accomplish this same thing in the OBIEE? I see the CAST function, but there doesn't seem to be any way to cast a string to a date?The original post is 4 years old - I am sure the poster must have figured it out by this time... obiee 11g supports a To_Datetime function though! thanks!
-
Convert varchar to date in BO Universe with Substring and instring function
to_date(substr(xxxx_v.e_details,instr(xxxx_v.e_details,'|',1,2)+1,9),'DD-MM-YYYY') In the universe while defining the object as date i was facing probs can any body help me out. the column xxxx_e_details is having the datatype varchar in database and the third string is date while i was creating the date object in the universe with the above syntax it was getting the error
The data in this obect is like this xxxx_v.e_details -> wwww|eeee|MM-DD-YY|
Edited by: mohammed kashif on Mar 31, 2011 11:47 AMi am getting the data but it is in the format 01-03-0201. The year format for 2010 is populating as 0201. i am not able to think whether it is due to instring function which is reading data like this. Need suggestion from experts.............
-
Convert VARCHAR to date in OBIEE
I have an column Period Name and data as
DEC-04
DEC-05
DEC-07
I want to convert into date format ..so is there any way...i tried with cast but it through error.
Thanks,
Shi s,
Try this out :http://varanasisaichand.blogspot.com/2010/01/how-to-change-data-format-to-our-custom.html
or use evaluate function
http://varanasisaichand.blogspot.com/2010/05/evaluate-function.html
Thanks,
Saichand.v -
Hi All
when i run the below select statement i get error message. pay_dt is varchar2(8) data type.
ORA-01861 : literal does not match format string
Any help on this appreciated. Thank you very much.
SELECT DISTINCT to_char(to_date(pay_dt
,'YYYY-MM-DD')
,'MON')
from paymentsMahir M. Quluzade wrote:
Your pay_dt datatype varchar2(8), but your gived format YYYY-MM-DD length is 10.
Change yor format please to 'YYYYMMDD' or 'DDMMYYYY' or 'MMDDYYYY' or 'YYYYDDMM' for your payments.pay_dt data.
for examle : pay_dt is '20010528' then use 'YYYYMMDD'unfortunately probably not the case - oracle is surprisingly forgiving with dates and will ignore any separators you add in your format mask if it can still convert it.
SQL> create table foo (dte varchar2(8));
Table created.
Elapsed: 00:00:00.00
SQL> insert into foo values ('20110101');
1 row created.
Elapsed: 00:00:00.00
SQL>
SQL> select to_date(dte,'yyyy-mm-dd') from foo;
TO_DATE(DTE,'YYYY-M
2011-01-01 00:00:00
1 row selected.I'd recommend searching through the data to find the record(s) that are completely around the wrong way or contain invalid characters etc. -
Convert work area data into comma separator format ( CSV format )
the function moudule sap_convert_to_csv_format is not available in my system . it is a not released fm as of now. so i cant use it.
My requirement is to send the details to app server in a comma separated format.
For each work area , which i transfer to application server, i hv to separte each field by a comma separtaor.
TRANSFER wa to VA_FILENAME LENGTH 256 ENF OF LINE.
Suppose my work area has fields wa-f1 wa-f2 wa-f3, it should write in app server as value1, value2, value3 like wise....
Suggest me if there is any alternative function module to acheiver this like when we pass wa to fm, the fields should be comma separator,
Any other useful suggestions are welcome.
ThanksHi,
here is the piece of code to transfer data from internal table to applivcation server as a comma seperated file..
FORM comma_sep_file .
DATA: l_cost_center_str TYPE type_cost_center.
IF it_cost_center[] IS NOT INITIAL.
**Concatenate file path and file name
CONCATENATE p_cpath p_cfile INTO v_cost_cen_output.
OPEN DATASET v_cost_cen_output FOR OUTPUT IN TEXT MODE ENCODING DEFAULT.
If Network file could not be opened, give a message.
IF sy-subrc <> 0.
WRITE : / text-030 , v_cost_cen_output .
MESSAGE s000(zp) WITH text-015 .
CLEAR : v_cost_cen_output,
p_cpath .
ELSE.
LOOP AT it_cost_center INTO l_cost_center_str.
CONCATENATE l_cost_center_str-co_cen_code
l_cost_center_str-co_cen_name
l_cost_center_str-fld3
l_cost_center_str-fld4
l_cost_center_str-set_true INTO wa_csvdata
SEPARATED BY c_const_sep.
TRANSFER wa_csvdata TO v_cost_cen_output.
CLEAR wa_csvdata.
ENDLOOP.
ENDIF."IF sy-subrc <> 0.
CLOSE DATASET v_cost_cen_output.
ENDIF.
ENDFORM. "
i hope this will help you...
Thanks & Regards
Ashu Singh -
How to Convert Calender to Date
Hi.
I have Calender object (MM dd,yyyy), I wanted to convert this into Date object in the format of "yyyy-mm-dd". Can any one please give me code to do this ?
Thanks
Sarav.Use Calendar.getTime() to get a Date object corresponding to the point in time that the Calendar represents.
But note that Dates don't have formats. If you want the time formatted in a particular way, use a java.text.SimpleDateFormat. -
How to Convert internal table data into text output and send mail in ABAP
Hi All,
Good Morning.
Taking a glance at a code that converts internal table data to an Excel file in ABAP. also checked how to send this excel to mailing list as attachment.
But thought of doing it without excel.
I mean, I have an internal table which contains fields of all types (character,integer,date,time). Since it is only around 4 to 5 rows in it (output),why to convert it to excel. not required!!. Instead I want to send this output to User's mails as Normal mail body with No attachments.
Could anybody please suggest me a way as to how to send internal table data as a mail ( not as an excel or PDF etc).
as of now my findings are, it is quite complex to convert internal table data to email (Text) format. but i believe if there is some way of doing it.
Best Regards
Dileep VThere's something I have used in the past where we send out information about failed precalculation settings (which are stored in internal table gt_fail)
notice we use gt_text as "mail body"
TRY.
* -------- create persistent send request ------------------------
gv_send_request = cl_bcs=>create_persistent( ).
* -------- create and set document -------------------------------
* create text to be sent
wa_line = text-001.
APPEND wa_line TO gt_text.
CLEAR wa_line.
APPEND wa_line TO gt_text.
LOOP AT gt_fail ASSIGNING <fs_fail>.
MOVE <fs_fail>-retry_count TO gv_count.
CONCATENATE text-002
<fs_fail>-setting_id
text-003
gv_count
INTO wa_line SEPARATED BY space.
APPEND wa_line TO gt_text.
CLEAR wa_line.
ENDLOOP.
APPEND wa_line TO gt_text.
wa_line = text-007.
APPEND wa_line TO gt_text.
* create actual document
gv_document = cl_document_bcs=>create_document(
i_type = 'RAW'
i_text = gt_text
i_length = '12'
i_subject = 'Failed Precalculation Settings!' ).
* add document to send request
CALL METHOD gv_send_request->set_document( gv_document ).
* --------- set sender -------------------------------------------
gv_sender = cl_sapuser_bcs=>create( sy-uname ).
CALL METHOD gv_send_request->set_sender
EXPORTING
i_sender = gv_sender.
* --------- add recipient (e-mail address) -----------------------
LOOP AT s_email INTO wa_email.
MOVE wa_email-low TO gv_email.
gv_recipient = cl_cam_address_bcs=>create_internet_address(
gv_email ).
CALL METHOD gv_send_request->add_recipient
EXPORTING
i_recipient = gv_recipient
i_express = 'X'.
ENDLOOP.
* ---------- set to send immediately -----------------------------
CALL METHOD gv_send_request->set_send_immediately( 'X' ).
* ---------- send document ---------------------------------------
CALL METHOD gv_send_request->send(
EXPORTING
i_with_error_screen = 'X'
RECEIVING
result = gv_sent_to_all ).
IF gv_sent_to_all = 'X'.
WRITE text-004.
ENDIF.
COMMIT WORK.
* exception handling
CATCH cx_bcs INTO gv_bcs_exception.
WRITE: text-005.
WRITE: text-006, gv_bcs_exception->error_type.
EXIT.
ENDTRY.
with the following declarations
* TABLES *
TABLES:
adr6,
rsr_prec_sett.
* INTERNAL TABLES & WORK AREAS *
DATA:
gt_fail TYPE SORTED TABLE OF rsr_prec_sett
WITH UNIQUE KEY setting_id run_date,
gt_text TYPE bcsy_text,
wa_fail LIKE LINE OF gt_fail,
wa_line(90) TYPE c.
FIELD-SYMBOLS:
<fs_fail> LIKE LINE OF gt_fail.
* VARIABLES *
DATA:
gv_count(4) TYPE n,
gv_send_request TYPE REF TO cl_bcs,
gv_document TYPE REF TO cl_document_bcs,
gv_sender TYPE REF TO cl_sapuser_bcs,
gv_recipient TYPE REF TO if_recipient_bcs,
gv_email TYPE adr6-smtp_addr,
gv_bcs_exception TYPE REF TO cx_bcs,
gv_sent_to_all TYPE os_boolean.
* SELECTION-SCREEN *
SELECT-OPTIONS:
s_email FOR adr6-smtp_addr NO INTERVALS MODIF ID sel.
DATA:
wa_email LIKE LINE OF s_email. -
Problem in Converting String to Date
Hi All,
I am having one String
String date = "2006-01-17 15:19:57.0"
I want to parse this String into Date object.
I will really appriciate if somebody helps me out.
Thanks.You're specifying a 'T' and a timezone in your format, but they're not present in the string you're parsing.
I'm assuming from the way you're printing out the date, that your thinking is along these lines: "sdfInput will parse the input string, no matter what format it's in, and will produce a Date object. That Date object wil have the format specified in sdfInput."
This is wrong on a couple of fronts:
1) DateFormat doesn't magically figure out what format it's supposed to use for the String it's parse()ing. The String has to match the DF's format.
2) Dates don't have formats. Only Strings do. A Date object is just a long. There's no relationship whatsoever between the Date that you get from parse() and the format that was used to produce it. When you print out a Date as you're doing, its toString method is called, which in turn uses a default format for your Locale.
If you want to turn a date string in one format into a date string in another format, use two different DateFormat objects with two different formats. Date date = df1.parse(inputString);
String outputString = df2.format(date);
Maybe you are looking for
-
Can you validate an XMLElement that uses the default namespace?
We have a partner that we communicate with via XML over HTTP and the schema that they gave us for their request/response does not specify a namespace. I am able to import the schema and create variables from its elements to send the request and get a
-
Interactive funcationality not working
Hello, The sorting and filtering functions are not working in any interactive reports in an application. The interactive report appears when sorting or filtering, the waiting symbol is shown but there is no sorting or filtering. I think it may have t
-
Can anyone correct the code in a right way...
Hi Friends I am implementing the BADI : HRHAP00_ENHANCE_FRE1 ~ENHANCE_DOCUMENT. Actually the BADI conatains the following code for inserting the single objectives at a time to a template. includes include: incl_hap_messages, incl_hap_ele
-
I have a problem with the solution
import java.util.*; public class Group extends HashSet<Person>{ public static void main(String[] args){ Group g = new Group(); g.add(new Person("Hans")); g.add(new Person("Lotte")); g.add(new Person("Jane")); g.add(new Person(
-
I can not activate my CS2 Photoshop
I can not activate my CS2 Photoshop