Example usage for java.text DateFormat format

List of usage examples for java.text DateFormat format

Introduction

In this page you can find the example usage for java.text DateFormat format.

Prototype

public final String format(Date date) 

Source Link

Document

Formats a Date into a date-time string.

Usage

From source file:GetMultipleLeads.java

public static void main(String[] args) {
    System.out.println("Executing GetMultipleLeads");
    try {/*  w  w w  . j  a  v  a  2s .c  om*/
        URL marketoSoapEndPoint = new URL("CHANGE ME" + "?WSDL");
        String marketoUserId = "CHANGE ME";
        String marketoSecretKey = "CHANGE ME";

        QName serviceName = new QName("http://www.marketo.com/mktows/", "MktMktowsApiService");
        MktMktowsApiService service = new MktMktowsApiService(marketoSoapEndPoint, serviceName);
        MktowsPort port = service.getMktowsApiSoapPort();

        // Create Signature
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String text = df.format(new Date());
        String requestTimestamp = text.substring(0, 22) + ":" + text.substring(22);
        String encryptString = requestTimestamp + marketoUserId;

        SecretKeySpec secretKey = new SecretKeySpec(marketoSecretKey.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] rawHmac = mac.doFinal(encryptString.getBytes());
        char[] hexChars = Hex.encodeHex(rawHmac);
        String signature = new String(hexChars);

        // Set Authentication Header
        AuthenticationHeader header = new AuthenticationHeader();
        header.setMktowsUserId(marketoUserId);
        header.setRequestTimestamp(requestTimestamp);
        header.setRequestSignature(signature);

        // Create Request
        ParamsGetMultipleLeads request = new ParamsGetMultipleLeads();

        // Request Using LeadKey Selector
        ////////////////////////////////////////////////////////
        LeadKeySelector keySelector = new LeadKeySelector();
        keySelector.setKeyType(LeadKeyRef.EMAIL);

        ArrayOfString aos = new ArrayOfString();
        aos.getStringItems().add("formtest1@marketo.com");
        aos.getStringItems().add("joe@marketo.com");
        keySelector.setKeyValues(aos);
        request.setLeadSelector(keySelector);

        /*
        // Request Using LastUpdateAtSelector
        ////////////////////////////////////////////////////////
        LastUpdateAtSelector leadSelector = new LastUpdateAtSelector();
                 
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTimeInMillis(new Date().getTime());
        gc.add( GregorianCalendar.DAY_OF_YEAR, -2);
                 
        DatatypeFactory factory = DatatypeFactory.newInstance();
                
        ObjectFactory objectFactory = new ObjectFactory();
        JAXBElement<XMLGregorianCalendar> until =objectFactory.createLastUpdateAtSelectorLatestUpdatedAt(factory.newXMLGregorianCalendar(gc));            
                 
        GregorianCalendar since = new GregorianCalendar();
        since.setTimeInMillis(new Date().getTime());
        since.add( GregorianCalendar.DAY_OF_YEAR, -5);
                 
        leadSelector.setOldestUpdatedAt(factory.newXMLGregorianCalendar(since));
        leadSelector.setLatestUpdatedAt(until);     
                 
        request.setLeadSelector(leadSelector);
        */

        /*
        // Request Using StaticList Selector
        ////////////////////////////////////////////////////////
        StaticListSelector staticListSelector = new StaticListSelector();
                
        //staticListSelector.setStaticListId(value)
        ObjectFactory objectFactory = new ObjectFactory();
        JAXBElement<String> listName = objectFactory.createStaticListSelectorStaticListName("SMSProgram.listForTesting");
        staticListSelector.setStaticListName(listName);
                 
        // JAXBElement<Integer> listId = objectFactory.createStaticListSelectorStaticListId(6926);
        // staticListSelector.setStaticListId(listId);
                 
        request.setLeadSelector(staticListSelector);
        */

        ArrayOfString attributes = new ArrayOfString();
        attributes.getStringItems().add("FirstName");
        attributes.getStringItems().add("AnonymousIP");
        attributes.getStringItems().add("Company");

        request.setIncludeAttributes(attributes);

        JAXBElement<Integer> batchSize = new ObjectFactory().createParamsGetMultipleLeadsBatchSize(10);
        request.setBatchSize(batchSize);

        SuccessGetMultipleLeads result = port.getMultipleLeads(request, header);

        JAXBContext context = JAXBContext.newInstance(SuccessGetLead.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(result, System.out);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:MainClass.java

public static void main(String[] args) {
    DateFormat shortDf = DateFormat.getDateInstance(DateFormat.SHORT);

    DateFormat mediumDf = DateFormat.getDateInstance(DateFormat.MEDIUM);
    DateFormat longDf = DateFormat.getDateInstance(DateFormat.LONG);
    DateFormat fullDf = DateFormat.getDateInstance(DateFormat.FULL);
    System.out.println(shortDf.format(new Date()));
    System.out.println(mediumDf.format(new Date()));
    System.out.println(longDf.format(new Date()));
    System.out.println(fullDf.format(new Date()));

    // parsing/*from   w ww .  j a v  a2s .c o  m*/
    try {
        Date date = shortDf.parse("Jan 32, 2005");
    } catch (ParseException e) {
    }
}

From source file:MainClass.java

public static void main(String[] args) {
    DateFormat shortDf = DateFormat.getDateInstance(DateFormat.SHORT);

    DateFormat mediumDf = DateFormat.getDateInstance(DateFormat.MEDIUM);
    DateFormat longDf = DateFormat.getDateInstance(DateFormat.LONG);
    DateFormat fullDf = DateFormat.getDateInstance(DateFormat.FULL);
    System.out.println(shortDf.format(new Date()));
    System.out.println(mediumDf.format(new Date()));
    System.out.println(longDf.format(new Date()));
    System.out.println(fullDf.format(new Date()));

    // parsing/*from   w  w w.  ja  va2 s  .co m*/
    try {
        Date date = shortDf.parse("12/12/2006");
    } catch (ParseException e) {
    }
}

From source file:MainClass.java

public static void main(String[] args) {
    Date today = new Date();
    Locale[] locales = { US, UK, GERMANY, FRANCE };
    int[] styles = { FULL, LONG, MEDIUM, SHORT };
    String[] styleNames = { "FULL", "LONG", "MEDIUM", "SHORT" };
    DateFormat fmt = null;
    for (Locale locale : locales) {
        System.out.println("\nThe Date for " + locale.getDisplayCountry() + ":");
        for (int i = 0; i < styles.length; i++) {
            fmt = DateFormat.getDateInstance(styles[i], locale);
            System.out.println("\tIn " + styleNames[i] + " is " + fmt.format(today));
        }/*ww w.  ja va2  s  . c  o  m*/
    }
}

From source file:bookChapter.theoretical.AnalyzeTheoreticalMSMSCalculation.java

/**
 *
 * @param args/*from  w  w w .  ja  va2s.  com*/
 * @throws IOException
 * @throws FileNotFoundException
 * @throws ClassNotFoundException
 * @throws InterruptedException
 * @throws MzMLUnmarshallerException
 */
public static void main(String[] args) throws IOException, FileNotFoundException, ClassNotFoundException,
        IOException, InterruptedException, MzMLUnmarshallerException {
    Logger l = Logger.getLogger("AnalyzeTheoreticalMSMSCalculation");
    Date date = Calendar.getInstance().getTime();
    DateFormat formatter = new SimpleDateFormat("EEEE, dd MMMM yyyy, hh:mm:ss.SSS a");
    String now = formatter.format(date);
    l.log(Level.INFO, "Calculation starts at {0}", now);
    double precursorTolerance = ConfigHolder.getInstance().getDouble("precursor.tolerance"),
            fragmentTolerance = ConfigHolder.getInstance().getDouble("fragment.tolerance");
    String databaseName = ConfigHolder.getInstance().getString("database.name"),
            spectraName = ConfigHolder.getInstance().getString("spectra.name"),
            output = ConfigHolder.getInstance().getString("output");
    int correctionFactor = ConfigHolder.getInstance().getInt("correctionFactor");
    boolean theoFromAllCharges = ConfigHolder.getInstance().getBoolean("hasAllPossCharge");
    BufferedWriter bw = new BufferedWriter(new FileWriter(output));
    bw.write("SpectrumTitle" + "\t" + "PrecursorMZ" + "\t" + "PrecursorCharge" + "\t" + "Observed Mass (M+H)"
            + "\t" + "AndromedaLikeScore" + "\t" + "SequestLikeScore" + "\t" + "PeptideByAndromedaLikeScore"
            + "\t" + "PeptideBySequestLikeScore" + "\t" + "LevenshteinDistance" + "\t" + "TotalScoredPeps"
            + "\t" + "isCorrectMatchByAndromedaLike" + "\t" + "isCorrectMatchBySequestLikeScore" + "\n");
    l.info("Getting database entries");
    // first load all sequences into the memory 
    HashSet<DBEntry> dbEntries = getDBEntries(databaseName);
    // for every spectrum-calculate both score...
    // now convert to binExperimental spectrum
    int num = 0;
    SpectrumFactory fct = SpectrumFactory.getInstance();
    num = 0;
    File f = new File(spectraName);
    if (spectraName.endsWith(".mgf")) {
        fct.addSpectra(f, new WaitingHandlerCLIImpl());
        l.log(Level.INFO, "Spectra scoring starts at {0}", now);
        for (String title : fct.getSpectrumTitles(f.getName())) {
            num++;
            MSnSpectrum ms = (MSnSpectrum) fct.getSpectrum(f.getName(), title);
            // here calculate all except this is an empty spectrum...
            if (ms.getPeakList().size() > 2) {
                // to check a spectrum with negative values..
                String text = result(ms, precursorTolerance, dbEntries, fragmentTolerance, correctionFactor,
                        theoFromAllCharges);
                if (!text.isEmpty()) {
                    bw.write(text);
                }
            }
            if (num % 500 == 0) {
                l.info("Running " + num + " spectra." + Calendar.getInstance().getTime());
            }
        }
    }
    l.info("Program finished at " + Calendar.getInstance().getTime());

    bw.close();
}

From source file:com.rtl.http.Upload.java

public static void main(String[] args) throws Exception {

    if (args.length != 4) {
        // Jxj001 20150603 d:\rpt_rtl_0001.txt d:\confDir
        logger.error("??4,dataTypedataVersionfilePathconfDir");
        // System.out.println("??3,dataTypedataVersionfilePath");
        return;/*  www  .j a  v a 2 s  .c o m*/
    } else {
        Upload upload = new Upload();
        upload.readInfo(args[3]);

        Date date = new Date();
        DateFormat format1 = new SimpleDateFormat("yyyyMMdd");
        String todayDir = format1.format(date);

        File dir = new File(logDir + File.separator + todayDir);
        if (dir != null && !dir.exists()) {
            dir.mkdirs();
        }

        //         SimpleLayout layout = new SimpleLayout();
        PatternLayout layout = new PatternLayout("%d %-5p %c - %m%n");

        FileAppender appender = null;

        try {

            appender = new FileAppender(layout, dir.getPath() + File.separator + todayDir + "client.log", true);

        } catch (Exception e) {
            logger.error("");
        }

        logger.addAppender(appender);
        logger.setLevel(Level.INFO);

        InputStream fileIn;
        dataType = args[0];
        dataVersion = args[1];
        filePath = args[2];

        logger.info("dataType=" + dataType);
        logger.info("dataVersion=" + dataVersion);
        logger.info("filePath=" + filePath);

        try {
            File file = new File(filePath);
            if (!file.exists()) {
                // System.out.println("?:"+filePath);
                logger.error("?:" + filePath);
                return;
            }
            fileIn = new FileInputStream(filePath);
            String responseStr = send(upload.getJson(), fileIn, url);
            if (responseStr != null) {
                String[] values = responseStr.split(",");
                if ("ok".equals(values[0])) {
                    System.out.println("0");
                    logger.info("ok");
                } else {
                    System.out.println("1");
                    logger.info(" A" + values[1]);
                }
            } else {
                System.out.println("1");
                logger.info(" B????");
            }

        } catch (Exception e) {
            System.out.println("1");
            logger.error(" C" + e.getMessage());
        }
    }

    logger.info("??");
    // System.out.println("??");

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Date birth = null;//from w  w  w  .ja v  a 2 s  .c  o m
    String birthDate = "30-MAR-2012";
    DateFormat formatter = null;
    formatter = new SimpleDateFormat("dd-MMM-yyyy");
    birth = (Date) formatter.parse(birthDate); // birtDate is a string
    if (birth == null) {
        System.out.println("Birth object is still null.");
    } else {
        System.out.println("Default date format " + birth);
        System.out.println("Our SimpleDateFormat " + formatter.format(birth));
        System.out.println("Our SimpleDateFormat with all uppercase " + formatter.format(birth).toUpperCase());
    }
}

From source file:com.hp.mqm.atrf.Main.java

public static void main(String[] args) {

    long start = System.currentTimeMillis();
    setUncaughtExceptionHandler();//from  w ww  .j  a v a  2s.c  o m

    CliParser cliParser = new CliParser();
    cliParser.handleHelpAndVersionOptions(args);

    configureLog4J();
    logger.info(System.lineSeparator() + System.lineSeparator());
    logger.info("************************************************************************************");
    DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.getDefault());
    DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.getDefault());
    logger.info((String.format("Starting HPE ALM Test Result Collection Tool %s %s",
            dateFormatter.format(new Date()), timeFormatter.format(new Date()))));
    logger.info("************************************************************************************");

    FetchConfiguration configuration = cliParser.parse(args);
    ConfigurationUtilities.setConfiguration(configuration);

    App app = new App(configuration);
    app.start();

    long end = System.currentTimeMillis();
    logger.info(String.format("Finished creating tests and test results on ALM Octane in %s seconds",
            (end - start) / 1000));
    logger.info(System.lineSeparator());
}

From source file:com.traffic.common.utils.http.HttpClientUtils.java

public static void main(String[] args) {
    //cst??GMT?/*from  w  w  w .  j a v a  2s.c om*/
    DateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
    format.setTimeZone(TimeZone.getTimeZone("GMT"));
    String date = format.format(new Date());

    String s = "license_plate_num=%E7%B2%A4BA804D&engine_num=C32764&body_num=064484&city_pinyin=shenzhen";
    //??
    String SIGNATURE = MD5Encrypt.encrypt("POST&/v3/violations&" + date + "&" + s.length() + "&"
            + MD5Encrypt.encrypt("uTIYrJn6vJTyt1ztBNbqQQDexDjpAM4m"));
    //
    headers.put("Host", "api.buding.cn");
    headers.put("Authorization", "dLSQ1ZjK7exqlwqx:" + SIGNATURE);
    headers.put("Date", date);

    JSONObject reqParam = new JSONObject();
    reqParam.put("license_plate_num", "BA804D");
    reqParam.put("engine_num", "C32764");
    reqParam.put("body_num", "064484");
    reqParam.put("city_pinyin", "shenzhen");
    String respBody = HttpClientUtils.httpPost_JSONObject("http://api.buding.cn/v3/violations", reqParam);
    System.out.println(JSONObject.parse(respBody));
}

From source file:it.isislab.dmason.util.SystemManagement.Worker.thrower.DMasonWorker.java

public static void main(String[] args) {
    RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();

    ////  w w w . ja v  a2s .c  o m
    // Get name representing the running Java virtual machine.
    // It returns something like 6460@AURORA. Where the value
    // before the @ symbol is the PID.
    //
    String jvmName = bean.getName();

    //Used for log4j properties
    System.setProperty("logfile.name", "worker" + jvmName);

    //Used for log4j properties
    System.setProperty("steplog.name", "workerStep" + jvmName);

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss_SS");
    Date date = new Date();
    dateFormat.format(date);

    System.setProperty("timestamp", date.toLocaleString());

    System.setProperty("paramsfile.name", "params");
    try {
        File logPath = new File("Logs/workers");
        if (logPath.exists())
            FileUtils.cleanDirectory(logPath);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    logger = Logger.getLogger(DMasonWorker.class.getCanonicalName());
    logger.debug("StartWorker " + version);

    autoStart = false;
    connect = false;
    ip = null;
    port = null;
    String topic = "";
    updated = false;
    isBatch = false;
    topicPrefix = "";

    if (args.length == 0) {
        // Force waiting for beacon (requires ActiveMQWrapper)
        autoStart = false;
        connect = true;
    } else if (args.length == 2) {
        // Launched with IP and Port
        ip = args[0];
        port = args[1];
        autoStart = true;
        connect = true;
    } else if (args.length == 4) {
        // Used by D-Mason in order to restart a 
        // worker after update, batch execution, reset
        autoStart = true;
        ip = args[0];
        port = args[1];
        topic = args[2];
        if (args[3].equals("update")) {
            updated = true;
        }
        if (args[3].equals("reset")) {
            updated = false;
            isBatch = false;
        }
        if (args[3].contains("Batch")) {
            updated = false;
            isBatch = true;
            topicPrefix = args[3];
        }
    } else {
        System.out.println("Usage: StartWorker IP PORT");
    }

    DMasonWorker worker = new DMasonWorker(ip, port, topic);

    boolean connected = worker.startConnection();

    if (connected) {
        logger.debug("CONNECTED:");
        logger.debug("   IP     : " + worker.ipAddress.getIPaddress());
        logger.debug("   Port   : " + worker.ipAddress.getPort());
        logger.debug("   Prefix : " + DMasonWorker.topicPrefix);
        logger.debug("   Topic  : " + worker.myTopic);
    } else {
        logger.info("CONNECTION FAILED:");
        logger.debug("   IP     : " + worker.ipAddress.getIPaddress());
        logger.debug("   Port   : " + worker.ipAddress.getPort());
        logger.debug("   Prefix : " + DMasonWorker.topicPrefix);
        logger.debug("   Topic  : " + worker.myTopic);
    }
}