Format a Timestamp from a String

I get an "incompatible types, found java.util.date, expecting java.sql.date" error when I try to do the following:
java.sql.Timestamp myTime = new Timestamp(0);
SimpleDateFormat TIME_PARSER = new SimpleDateFormat("h:mm a");
String myTimeString = TIME_PARSER.format(myTime);I think it expects the parser to be an sql date rather than a util.date.

I get an "incompatible types, found java.util.date, expecting java.sql.date" errorGive java what it is asking for: the variable of type java.util.date
Try to change the first line to this:
Date myTime = new Date();It creates a variable representing the current date and time on your computer.
Regards,
Martin

Similar Messages

  • How can I export formatted text from a string indicator?

    Does someone know how I can export formatted text (i.e., parts of the text have different formatting, such as color, fontsize, etc.) from a string indicator? Using copy/paste does not work, as it only exports unformatted plain text.

    Hello Sparti,
        Thank you for your suggestions, they are all very useful, and I plan to use the HTML feature under Report Generation to export the formatted text from Labview. However, I am still not sure how I can extract the formatted text from a *string indicator* and transfer it to one of those VIs, so that it can be exported to other applications. Let me give some more specific info on what I am trying to achieve:  I am monitoring the communication between two pieces of equipment. A string indicator shows all the data flow, with different colors for data coming from different instruments. I managed to do that by using a property node and playing with the selection and font color properties. Now, if you just wire the output of the string indicator, the formatting is gone and all you get is just plain black text (for instance, try to programmatically transfer the formatted text from one string indicator to a different string indicator and you will see that the formatting is not preserved). Even if you try the "brute force" method of manually selecting and copying the text in the indicator and pasting it to Word, LV does not export the formatting. But, if you paste *within*  LV (for example, paste it to a string constant in your diagram), then it works. To extract the formatted string from the indicator, I also tried to use a property node, but without success. I am trying to avoid duplicating part of my code to generate the same color-coding scheme on a report. It would be way easier to be able to transfer the formatted text from the string indicator. This is particularly annoying, because the information is there, stored in the data structure associated with the string indicator. But how can I put my hands on it? Any ideas?

  • Formatting a timestamp into string with $ specifier

    Formatting a timestamp into string with $ specifier does not work; the formatted string is empty and no error is reported:
    I have forced the width to 10 to show that the format is at least partially scanned but when it is omitted the timestamp field is empty.
    I couldn't find this problem reported/addressed so here it is (LabVIEW 8.6)
    LabVIEW, C'est LabVIEW

    Yes, the simple work around is to put the timestamp first in both the string and the inputs.  But this is a bug.  There is no doubt about that.  A high priority?  Probably not.  Something that should be looked for when doing a revamp of the Format String?  Yep.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • Extract min timestamp from string

    Hello all,
    I am trying to query the minimum datetime from a column that is stored as nvarchar(max). There a a few tricky things with this query (at least for me)
    - There is more than just the date being stored within each record. 
    -The position of the datetime is relative- although it does always appear in the format '**(DD-MM-YY at HH:MM PM' 
    -There are multiple datetimes stored in each record-so not only do I need to locate and capture where there is a datetime, I need to find the minimum datetime within the record
    - I can't just change the format that the data is stored in- there is over a decade of information that is stored this way.
    Please Help
    The column is called 'hdresp'
    Here is sample data:
    **(03-Apr-14 at 09:44 AM email sent) -- Billy Bob:  Upgrade ordered.    **(02-Apr-14 at 04:16 PM email sent) -- Sammy Richards:  I can give you another cable to if you think that will help but it just might be time for an upgrade.  If
    you want to go that route I have to ask that you submit another request for New Hardware.    **(02-Apr-14 at 03:17 PM email sent) -- Paul Smith:  Michael  Stop by my desk when you have a second.
    -What i would like to end up with is a query that identifies '02-Apr-14 at 3:17 PM' as the minimum time and converts it to 'YYYY-MM-DD HH:MM:SS' -for example '2014-04-02 15:17:00' 
    Thanks!

    Thank you everyone for your help!
    I ended up using this to extract and convert the minimum time from a string:
    SELECT CONVERT(datetime, REPLACE(LEFT(RIGHT(hdresp, PATINDEX('%(**%', REVERSE(hdresp)) - 1), 21), 'at ', ''))
    from tblhdmain
    where hdindex = 211458
    Which gave me the result:
    2014-04-02 15:17:00.000

  • How do I change TimeStamp from US server to UK time

    Hello,
    I am based in the UK. My hosting company is based in the US. I am using a MySql database. All the database tables have timestamps that are set to the local machine time.
    I would like to change the timestamp so that it is GMT.
    Can you please tell me how I would go about doing this?
    Is their any code available to enable me to insert the timestamp as a GMT date or do I set the value from the mysql database end.
    Thanks
    Andrew

    Timestamp values in Java (java.sql.Timestamp) are GMT internally (actually, they're implemented as a long giving the number of milliseconds since 1. january, 1970).
    Date values in SQL, on the other hand, are normally stored in the local time zone.
    What you need to do, is tell JDBC what time zone you want the stored values to be in, like this:
    When inserting (using a PreparedStatement):
      stmt.setTimestamp(column, myTimestamp, Calendar.getInstance(TimeZone.getTimeZone("GMT")));When reading back from a ResultSet:
      Timestamp ts = rs.getTimestamp(column, Calendar.getInstance(TimeZone.getTimeZone("GMT")));Now, you know that the timestamp value you've read back from the database does not have any bias to it introduced by the local timezone of the database server. The next step is to represent the Java Timestamp value to the user, and at this stage you may want to specify which time zone you want for the rendered timestamp, like this:
      import java.text.DateFormat;
      import java.text.SimpleDateFormat;
      // convert the Timestamp to a String in a controlled manner
      // see the documentation for SimpleDateFormat for how you specify the format string
      DateFormat df = new SimpleDateFormat("yyyy.MM.dd HH.mm.ss");
      // need to set the time zone, or the server's time zone will be used
      // if you can somehow figure out the time zone where the user is
      // sitting, you may use that instead, to provide dates relative to
      // the user instead of the server
      df.setTimeZone(TimeZone.getTimeZone("GMT"));
      String outValue = df.format(myTimestamp);
      // output the converted value, maybe
      System.out.println(outValue);Similarly, you may use the parse() method of DateFormat to parse a String as a java.util.Date, which may then be converted into a Timestamp.
    The general principles are as follows:
    - internally, Java Timestamps, Dates etc. are stored relative to 1. january 1970, GMT
    - when getting date values into or out of Java, time zones may have to be considered
    - for converting to/from Strings (eg. for UI purposes), use the java.text.DateFormat class
    - for communicationg with an SQL database via JDBC, use the set/get-Timestamp methods with the added Calendar argument
    NB! Please be aware that I didn't actually try to compile this code, so bugs may be present.

  • DateTimeFormatter.format() and date stored as string

    Greetings,
    I need to display some data in a spark data grid and would like to format a date from that data with a labelFunction calling a DateTimeFormatter's format function.
    The date is stored in my ArrayCollection in the following format '2004-05-03 01:03:52.0'
    my formatter is as follows
    <s:DateTimeFormatter id="dateFormatter" dateTimePattern="YYYY-MM-DD" />
    I would like my label function to return something like
    return "Date: " + dateFormatter.format( item[column.dataField]); // where the item[column.dataField] = "2004-05-03 01:03:52.0"
    The date is coming up blank. I'm thinking I need to convert the string "2004-05-03 01:03:52.0" to a Date object first, then pass that into the format() call.
    Is that the way to go? If so, what's the best way to handle that?
    Thanks

    Thank you Sumesh, but the problem was with getting the string converted to a date. I found a solution on
    http://polygeek.com/4137_actionscript3_batbelttime-utilities
    * Convert an MySQL Timestamp to an Actionscript Date
    * Thanks to Pascal Brewing [email protected] for the beautiful simplicity.
    public static function convertMySQLTimeStampToASDate( time:String ):Date{
    var pattern:RegExp = /[: -]/g;
    time = time.replace( pattern, ',' );
    var timeArray:Array = time.split( ',' );
    var date:Date = new Date( timeArray[0], timeArray[1]-1, timeArray[2],
    timeArray[3], timeArray[4], timeArray[5] );
    return date as Date;
    I pass in my string and it gets converted to a Date. I then pass the Date to the DateTimeFormatter.format() and everything works as expected.
    Thanks

  • Conversion failed when converting date and/or time from character string

    Hi experts,
    I'm trying running a query in Microsoft Query but it gives the following error message:
    "conversion failed when converting date and/or time from character string"
    when asks me the data I'm inserting 31-01-2014
    i've copy the query form the forum:
    SELECT T1.CardCode, T1.CardName, T1.CreditLine, T0.RefDate, T0.Ref1 'Document Number',
         CASE  WHEN T0.TransType=13 THEN 'Invoice'
              WHEN T0.TransType=14 THEN 'Credit Note'
              WHEN T0.TransType=30 THEN 'Journal'
              WHEN T0.TransType=24 THEN 'Receipt'
              END AS 'Document Type',
         T0.DueDate, (T0.Debit- T0.Credit) 'Balance'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')<=-1),0) 'Future'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=0 and DateDiff(day, T0.DueDate,'[%1]')<=30),0) 'Current'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>30 and DateDiff(day, T0.DueDate,'[%1]')<=60),0) '31-60 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>60 and DateDiff(day, T0.DueDate,'[%1]')<=90),0) '61-90 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>90 and DateDiff(day, T0.DueDate,'[%1]')<=120),0) '91-120 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=121),0) '121+ Days'
    FROM JDT1 T0 INNER JOIN OCRD T1 ON T0.ShortName = T1.CardCode
    WHERE (T0.MthDate IS NULL OR T0.MthDate > ?) AND T0.RefDate <= ? AND T1.CardType = 'C'
    ORDER BY T1.CardCode, T0.DueDate, T0.Ref1

    Hi,
    The above error appears due to date format is differnt from SAP query generator and SQL server.
    So you need convert all date in above query to SQL server required format.
    Try to convert..let me know if not possible.
    Thanks & Regards,
    Nagarajan

  • Trying to get a date value from a string

    Hi All,
    I'm not sure I am doing this right, so I figured I would ask the experts...
    I have built a file upload page that is working the way I need it, but I have found that I need to determine the date from the uploaded file name. I tried to create a PL/SQL computation and do some substr / instr to the filename, but I'm not getting it as I get "ORA-01843: not a valid month" error. Here is the code I'm trying:
    declare
      v_underscore  integer;
      v_date            varchar2(15);  --have also tried using date datatype...
    begin
      v_underscore := INSTR(:P20_EXPRESS,'_',1,1);
      v_date := to_date(substr(:P20_EXPRESS,v_underscore + 1,6),'YYMMDD');
      return v_date;
    end;And here is a sample filename:
    F15047/proc_10607161001.csv
    Is this the best way to achive what I'm trying to do?
    Thanks,
    Corey

    Hi,
    v_underscore := INSTR(:P20_EXPRESS,'_',1,1);
    v_date := to_date(substr(:P20_EXPRESS,v_underscore + 1,6),'YYMMDD');What this is saying is:
    Get the position of the "_" character
    Move to the next character to the right (which is a "1" in your case)
    Get 6 characters (106071) from the string value
    Convert them to a date using the format 'YYMMDD'
    This results in:
    Year: 10
    Month: 60
    Day: 71
    Which of course is not valid.
    For example:
    select
      substr('F15047/proc_10607161001.csv', instr('F15047/proc_10607161001.csv', '_', 1, 1) + 1, 6)
    from
      dual;
    SUBSTR
    106071It looks like you want to move two positions to the right rather than a single position:
    select
      substr('F15047/proc_10607161001.csv', instr('F15047/proc_10607161001.csv', '_', 1, 1) + 2, 6)
    from
      dual;
    SUBSTR
    060716Hope that helps a bit,
    Mark

  • How to create an XML document from a String.

    Can anyone help,
         In the Microsoft XML Document DOM there is a load function load(string) which will create an XML document, but now we are switching to Java and I do not know how to create and XML document from a string, this string �xml document� is passed to my program from a webservice and I need to read several xml elements form it in a web server.
    This string is a well formatted XML document:
    <?xml version="1.0" encoding="UTF-8"?>
    <Countries NumberOfRecords="1" LanguageID="en-us">
         <Country>
              <CountryCode>AU</CountryCode>
              <CountryName>AUSTRALIA</CountryName>
         </Country>
    </Countries>

    Thanks PC!
    I made it work using:
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    factory.setIgnoringComments(true); // We want to ignore comments
    // Now use the factory to create a DOM parser
    DocumentBuilder parser = factory.newDocumentBuilder();
    //TransformThisStringBuffer is a string buffer wich contain the 'XML document (String)'
    InputStream in = new ByteArrayInputStream(TransformThisStringBuffer.toString().getBytes());
    // Parse the InputStream and build the document
    Document document = parser.parse(in);
    But which one is faster InputSource or InputStream, were would you put the "new InputSource(new StringReader(yourString))" in the above code?

  • Setting the name of a new object from a string

    Is there anyway I can set the object name of a newly created
    object from a string?
    eg.
    (the code below generates a compile time error on the
    variable declaration)
    public function addText(newTxt:String, txt:String,
    format:TextFormat):void {
    var
    this[newTxt]:TextField = new TextField();
    this[newTxt].autoSize = TextFieldAutoSize.LEFT;
    this[newTxt].background = true;
    this[newTxt].border = true;
    this[newTxt].defaultTextFormat = format;
    this[newTxt].text = txt;
    addChild(this[newTxt]);
    called using>
    addText("mytxt", "test text", format);
    I could then reference the object later on without using
    array notation using mytxt.border = false; for example
    There are many a time when I want to set the name of a new
    object from a string.
    In this example I have a function that adds a new text object
    to a sprite.
    The problem is, if I call the function more than once then
    two textfield objects will exist, both with the same name. (either
    that or the old one will be overwritten).
    I need a way of setting the name of the textfield object from
    a string.
    using
    var this[newTxt]:TextField = new TextField()
    does not work, If I take the "var" keyword away it thinks it
    a property of the class not an object.
    resulting in >
    ReferenceError: Error #1056: Cannot create property newTxt on
    Box.
    There must be a way somehow to declare a variable that has
    the name that it will take represented in a string.
    Any help would be most welcome
    Thanks

    Using:
    var this[newTxt]:TextField = new TextField()
    is the right approach.
    You can either incrment an instance variable so that the name
    is unique:
    newTxt = "MyName" + _globalCounter;
    var this[newTxt]:TextField = new TextField();
    globalCounter ++;
    Or store the references in an array:
    _globalArray.push(new TextField());
    Tracy

  • Error "Conversion failed when converting date and/or time from character string" to execute one query in sql 2008 r2, run ok in 2005.

    I have  a table-valued function that run in sql 2005 and when try to execute in sql 2008 r2, return the next "Conversion failed when converting date and/or time from character string".
    USE [Runtime]
    GO
    /****** Object:  UserDefinedFunction [dbo].[f_Pinto_Graf_P_Opt]    Script Date: 06/11/2013 08:47:47 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE   FUNCTION [dbo].[f_Pinto_Graf_P_Opt] (@fechaInicio datetime, @fechaFin datetime)  
    -- Declaramos la tabla "@Produc_Opt" que será devuelta por la funcion
    RETURNS @Produc_Opt table ( Hora datetime,NSACOS int, NSACOS_opt int)
    AS  
    BEGIN 
    -- Crea el Cursor
    DECLARE cursorHora CURSOR
    READ_ONLY
    FOR SELECT DateTime, Value FROM f_PP_Graficas ('Pinto_CON_SACOS',@fechaInicio, @fechaFin,'Pinto_PRODUCTO')
    -- Declaracion de variables locales
    DECLARE @produc_opt_hora int
    DECLARE @produc_opt_parc int
    DECLARE @nsacos int
    DECLARE @time_parc datetime
    -- Inicializamos VARIABLES
    SET @produc_opt_hora = (SELECT * FROM f_Valor (@fechaFin,'Pinto_PRODUC_OPT'))
    -- Abre y se crea el conjunto del cursor
    OPEN cursorHora
    -- Comenzamos los calculos 
    FETCH NEXT FROM cursorHora INTO @time_parc,@nsacos
    /************  BUCLE WHILE QUE SE VA A MOVER A TRAVES DEL CURSOR  ************/
    WHILE (@@fetch_status <> -1)
    BEGIN
    IF (@@fetch_status = -2)
    BEGIN
    -- Terminamos la ejecucion 
    BREAK
    END
    -- REALIZAMOS CÁLCULOS
    SET @produc_opt_parc = (SELECT dbo.f_P_Opt_Parc (@fechaInicio,@time_parc,@produc_opt_hora))
    -- INSERTAMOS VALORES EN LA TABLA
    INSERT @Produc_Opt VALUES (@time_parc,@nsacos, @produc_opt_parc)
    -- Avanzamos el cursor
    FETCH NEXT FROM cursorHora INTO @time_parc,@nsacos
    END
    /************  FIN DEL BUCLE QUE SE MUEVE A TRAVES DEL CURSOR  ***************/
    -- Cerramos el cursor
    CLOSE cursorHora
    -- Liberamos  los cursores
    DEALLOCATE cursorHora
    RETURN 
    END

    You can search the forums for that error message and find previous discussions - they all boil down to the same problem.  Somewhere in your query that calls this function, the code invoked implicitly converts from string to date/datetime.  In general,
    this works in any version of sql server if the runtime settings are correct for the format of the string data.  The fact that it works in one server and not in another server suggests that the query executes with different settings - and I'll assume for
    the moment that the format of the data involved in this conversion is consistent within the database/resultset and consistent between the 2 servers. 
    I suggest you read Tibor's guide to the datetime datatype (via the link to his site below) first - then go find the actual code that performs this conversion.  It may not be in the function you posted, since that function also executes other functions. 
    You also did not post the query that calls this function, so this function may not, in fact, be the source of the problem at all. 
    Tibor's site

  • How to extract an integer or a float value from a String of characters

    Hi i have a problem getting to a float value within a string of characters..
    for instance the string is
    "numberItem xxxxxxxxx 700.0" (each x is a space..the forum wouldnt let me put normal spaces for some reason)
    how do i store 700.0 in a float variable
    remember the string is obtained from an inputfile
    so far i got the program to store the inputfile data line by line in a String array..i tried tokenizing the string to get to the the float value but since i have mulitple spaces within my string, the token method only gets "numberItem" from the above String
    This is all i have so far:
    String c;
    String Array[] =new String[g]; (i used a while loop to obtain g(the nubmer of lines in the file))
    while((c=(cr.readLine()))!=null)
    Array[coun]=c;
    it would be reallllllllllllllllllllllllllllllllllllllly easy if there was a predefined method to extract numeric values from a string in java..
    Edited by: badmash on Feb 18, 2009 5:50 PM
    Edited by: badmash on Feb 18, 2009 5:50 PM
    Edited by: badmash on Feb 18, 2009 5:55 PM

    badmash wrote:
    Hi i have a problem getting to a float value within a string of characters..
    for instance the string is
    "numberItem xxxxxxxxx 700.0" (each x is a space..the forum wouldnt let me put normal spaces for some reason)
    with the space included
    how do i store 700.0 in a float variable
    remember the string is obtained from an inputfile
    so far i got the program to store the inputfile data line by line in a String array..i tried tokenizing the string to get to the the float value but since i have mulitple spaces within my string, the token method only gets "numberItem" from the above StringHuh?
    Not true.
    Anyway why not use string split, split on spaces and grab the last element (which by the format you posted would be your 700.0)
    Then there is the Float.parseFloat method.
    It is easy.
    And another thing why not use a List of Strings if you want to store each line? (And why did you post that code which doesn't really have anything to do with your problem?) Also in future please use the code formatting tags when posting code. Select the code you are posting in the message box and click the CODE button.

  • How can I change the formate of @today from (MM/dd/yyy) to (dd-MM-yyyy)?

    I am in openscript, using a settext commend - .setText("{{@today(MM/dd/yyyy), 10-02-2011}}}}"); is anyone know how can I change the formate of @today from (MM/dd/yyy) to (dd-MM-yyyy)?
    I went to Java Code tab and tried to use - new SimpleDataFormat("dd-MM-yyyy").format(new Date()); but not successful. Any help will be appreciated.
    Katherine

    Hi,
    you can display the date format in dd-mm-yy by using the below Java code.
    First import the bellow java classes.
    import java.util.Date;
    import java.text.SimpleDateFormat;
    //and add bellow code in run() function
         //************ Display Date and Time *************
         Date date_format=new Date();
         SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");// HH:mm:ss");
         String Exec_Time = dateFormat.format(date_format);
    //output statement
    info("Today's Date: "+Exec_Time);
    I can able to add the screenshot of this output here, so if you need any other information please write to me.
    Regards,
    MRSN

  • How to use JEditorPanel to display an HTML page from a String?

    Hi,
    I need to store a report in HTML format which is store in String and when I use JEditorPane.setText to insert the string and JeditorPane refused to display and content or just the String "<HTML> <HEAD>..." in plain text. SHould I use other method to do the job?
    I also need to print it out from the Jeditorpane too. What do u suggest?
    Thanks.

    I got the HTML stuff working just yesterday. I don't know if there is a "more correct" solution:
            String message = "<head></head><body>Blagh blagh</body>";
            JEditorPane textpane = new JEditorPane();
            HTMLEditorKit kit = new HTMLEditorKit();
            textpane.setEditorKit(kit);
            textpane.setText(message);If you're not having luck then it may be because your HTML is wrong. I know that if I had poorly constructed HTML then it did originally display as plaintext.

  • Lost Milliseconds when getting timestamp from database

    I store a timestamp in DB2 by formatting the current timestamp using the following format mask :
    "yyyy-MM-dd-H.mm.ss.SSS". I query the database and the milliseconds are there. When I retrieve a resultset from the database and get the column using rs.getTimestamp(), I reformat it using the same formatting mask and LOSE all the milliseconds. I believe I'm losing the milliseconds when I execute the getTimestamp() method. What do I have to do to get the entire timestamp from the database, including the milliseconds?

    I pulled this quote directly out of the jdk docs:
    "If a time value that includes the fractional seconds is desired, you must convert nanos to milliseconds (nanos/1000000)"
    the timestamp doesn't actually have a millisecond value. You can get it by calling the getNanos() function and /1000000.
    you might be losing the millisecond value because there isn't a millisecond value, only nanoseconds.
    good luck
    Jamie

Maybe you are looking for

  • How do I move up one folder while browsing Time Machine?

    When I'm viewing a folder in Time Machine's "Star Wars" view, how do I move up one folder, to view the current folder's parent folder? In Finder, I have several ways to do it: I could either hit CMD+Up Arrow, or CMD-click the title bar then click on

  • I keep getting an error in connecting to the cloud

    Can't connect Icloud from my HP laptop  Keep getting Error

  • Install dramas with creative suite trial

    I purchased the dvd of adobe creative suite 3 trial and need to install photoshop from the disks. When I install I get message photoshop already installed so I cant install it I have removed all reference to an earlier trial of photoshop which had no

  • Image upload from Elements 11 Organizer

    Hi, Just wondering if anyone can tell me how to upload images from an album in Elements 11 Organizer to an online print service? I am using a Mac OSX 10.9.2. Many thanks, Graham

  • Empties Processing -IS Retail

    Hi I had created a Article as Full product with Material Type "VOLL" and two empties articles with Material Type "LGUT". In Full product (Basic Data view) i had activated "with empties BOM". While creating Purchase Order, when i entered the full prod