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:com.netflix.scheduledactions.triggers.IntervalTrigger.java

/**
 * Creates an interval trigger based on the given parameters
 *///www  .java2s .  c o m
public IntervalTrigger(int interval, TimeUnit intervalUnit, int repeatCount, Date startAt) {
    if (interval <= 0) {
        throw new IllegalArgumentException(
                String.format("Invalid interval %s specified for the IntervalTrigger", interval));
    }
    if (startAt == null) {
        startAt = new Date();
    }
    DateFormat dateFormat = new SimpleDateFormat(ISO_8601_DATE_FORMAT);
    this.iso8601Interval = String.format("%s/%s%s%s", dateFormat.format(startAt), ISO_8601_TIME_PREFIX,
            interval, intervalUnit.getTimeUnitSuffix());
    this.repeatCount = repeatCount;
}

From source file:com.sammyun.util.DateUtil.java

public static String obtainMonth(String dateStr, int m) {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    String str = "";
    try {//from w w  w  . j a  v a  2 s  .co m
        Date d1 = df.parse(dateStr);
        Calendar g = Calendar.getInstance();
        g.setTime(d1);
        g.add(Calendar.MONTH, m);
        Date d2 = g.getTime();
        str = df.format(d2);
        str = str.replace("-", "");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return str;
}

From source file:marytts.tools.dbselection.DatabaseSelector.java

/**
 * Main method to be run from the directory where the data is.
 * Expects already computed unit features in directory unitfeatures.
 * /*from  www.ja va 2s .  c o m*/
 * @param args the command line args (see printUsage for details)
 * 
 * @return the array of feature vectors used in the current pass
 */
public static void main2(String[] args) throws Exception {
    /* Sort out the filenames and dirs for the logfiles */
    System.out.println("Starting Database Selection...");

    long time = System.currentTimeMillis();
    PrintWriter logOut;

    String dateString = "", dateDir = "";
    DateFormat fullDate = new SimpleDateFormat("dd_MM_yyyy_HH_mm_ss");
    DateFormat day = new SimpleDateFormat("dd_MM_yyyy");
    Date date = new Date();
    dateString = fullDate.format(date);
    dateDir = day.format(date);

    System.out.println("Reading arguments ...");
    StringBuffer logBuf = new StringBuffer();
    if (!readArgs(args, logBuf)) {
        throw new Exception("Something wrong with the arguments.");
    }

    //make sure the stop criterion is allright
    SelectionFunction selFunc = new SelectionFunction();
    if (!selFunc.stopIsOkay(stopCriterion)) {
        System.out.println("Stop criterion format is wrong: " + stopCriterion);
        printUsage();
        throw new Exception("Stop criterion format is wrong: " + stopCriterion);
    }

    //make various dirs
    File selectionDir = new File(selectionDirName);
    if (!selectionDir.exists())
        selectionDir.mkdir();
    File dateDirFile = new File(selectionDirName + dateDir);
    if (!dateDirFile.exists())
        dateDirFile.mkdir();

    //open log file
    String filename = selectionDirName + dateDir + "/selectionLog_" + dateString + ".txt";
    try {
        logOut = new PrintWriter(new BufferedWriter(new FileWriter(new File(filename))), true);
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("Error opening logfile");
    }
    //print date and arguments to log file
    logOut.println("Date: " + dateString);
    logOut.println(logBuf.toString());

    wikiToDB = new DBHandler(locale);

    // Check if name of selectedSentencesTable has to be changed
    if (selectedSentencesTableName != null)
        wikiToDB.setSelectedSentencesTableName(selectedSentencesTableName);
    else
        System.out.println("Current selected sentences table name = " + selectedSentencesTableName);

    // If connection succeed
    if (wikiToDB.createDBConnection(mysqlHost, mysqlDB, mysqlUser, mysqlPasswd)) {

        /* Read in the feature definition */
        System.out.println("\nLoading feature definition...");
        try {
            BufferedReader uttFeats = new BufferedReader(
                    new InputStreamReader(new FileInputStream(new File(featDefFileName)), "UTF-8"));
            featDef = new FeatureDefinition(uttFeats, false);
            uttFeats.close();
            System.out.println(
                    "TARGETFEATURES:" + featDef.getNumberOfFeatures() + " =  " + featDef.getFeatureNames());
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("Error opening featureDefinition file");
        }

        System.out.println("Getting a list of ids for all the sentences in the DB...");
        System.out.println("(if the number of sentences is large, this can take a while)");
        System.out.println();
        String condition = null;
        if (considerOnlyReliableSentences) {
            condition = "reliable=true";
        }
        CoverageFeatureProvider cfp;
        if (holdVectorsInMemory) {
            /* Load the feature vectors from the database */
            System.out.println("Will also load feature vectors into memory (increase memory if this fails)");
            Pair<int[], byte[][]> pair = wikiToDB.getIdsAndFeatureVectors("dbselection", condition);
            int[] sentenceIDs = pair.getFirst();
            byte[][] vectorArray = pair.getSecond();
            cfp = new InMemoryCFProvider(vectorArray, sentenceIDs);
        } else {
            cfp = new DatabaseCFProvider(wikiToDB, condition);
        }

        /* Initialise the coverage definition */
        System.out.println("\nInitiating coverage...");
        CoverageDefinition covDef = new CoverageDefinition(featDef, cfp, covDefConfigFileName);

        // If the selectedSentencesTable is new, (does not exist) then a new table
        // will be created, the selected field in the dbselection table will be initialised to selected=false. 
        // The sentences already marke in this db as unwanted=true will be kept. 
        wikiToDB.createSelectedSentencesTable(stopCriterion, featDefFileName, covDefConfigFileName);
        // With the information provided by the user
        wikiToDB.setTableDescription(wikiToDB.getSelectedSentencesTableName(), tableDescription, stopCriterion,
                featDefFileName, covDefConfigFileName);

        long startTime = System.currentTimeMillis();
        File covSetFile = new File(initFileName);
        boolean readCovFromFile = true;
        if (!covSetFile.exists()) {
            //coverage has to be initialised
            readCovFromFile = false;
            covDef.initialiseCoverage();
            System.out.println("\nWriting coverage to file " + initFileName);
            covDef.writeCoverageBin(initFileName);
        } else {
            condition = null;
            if (considerOnlyReliableSentences) {
                condition = "reliable=true";
            }
            int[] idSentenceList = wikiToDB.getIdListOfType("dbselection", condition);
            covDef.readCoverageBin(initFileName, idSentenceList);
        }

        /* add already selected sentences to cover */
        System.out.println("\nAdd to cover already selected sentences marked as unwanted=false.");
        selectedIdSents = new LinkedHashSet<Integer>();
        addSelectedSents(selectedSentencesTableName, covDef);

        /* remove unwanted sentences from basename list */
        System.out.println("\nRemoving selected sentences marked as unwanted=true.");
        unwantedIdSents = new LinkedHashSet<Integer>();
        removeUnwantedSentences(selectedSentencesTableName);

        long startDuration = System.currentTimeMillis() - startTime;
        if (verbose)
            System.out.println("Startup took " + startDuration + " milliseconds");
        logOut.println("Startup took " + startDuration + " milliseconds");

        /* print text corpus statistics */
        if (!readCovFromFile) {
            //only print if we did not read from file
            filename = selectionDirName + "textcorpus_distribution.txt";
            System.out.println("Printing text corpus statistics to " + filename + "...");
            PrintWriter out = null;
            try {
                out = new PrintWriter(new FileWriter(new File(filename)), true);
                covDef.printTextCorpusStatistics(out);
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("Error printing statistics");
            } finally {
                out.close();
            }
        }

        //print settings of the coverage definition to log file 
        covDef.printSettings(logOut);

        /* Start the algorithm */
        System.out.println("\nSelecting sentences...");

        // If it is not already running (could happen when SynthesisScriptGUI is used)
        // Start builtin MARY TTS in order to get and save the transcription 
        // of the selected sentences (selected_text_transcription.log)
        if (Mary.currentState() == Mary.STATE_OFF) {
            System.out.print("Starting builtin MARY TTS...");
            Mary.startup();
            System.out.println(" MARY TTS started.");
        }

        //selFunc.select(selectedSents,covDef,logOut,basenameList,holdVectorsInMemory,verbose);
        selFunc.select(selectedIdSents, unwantedIdSents, covDef, logOut, cfp, verbose, wikiToDB);

        /* Store list of selected files */
        filename = selectionDirName + dateDir + "/selectionResult_" + dateString + ".txt";
        //storeResult(filename,selectedSents);
        storeResult(filename, selectedIdSents);

        /* print statistics */
        System.out.println("Printing selection distribution and table...");
        String disFile = selectionDirName + dateDir + "/selectionDistribution_" + dateString + ".txt";
        String devFile = selectionDirName + dateDir + "/selectionDevelopment_" + dateString + ".txt";
        try {
            covDef.printSelectionDistribution(disFile, devFile, logCovDevelopment);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("Error printing statistics");
        }

        if (overallLogFile != null) {
            //append results to end of overall log file
            PrintWriter overallLogOut = new PrintWriter(
                    new OutputStreamWriter(new FileOutputStream(new File(overallLogFile), true), "UTF-8"),
                    true);
            overallLogOut.println("*******************************\n" + "Results for " + dateString + ":");

            //overallLogOut.println("number of basenames "+basenameList.length);
            overallLogOut.println("number of basenames " + cfp.getNumSentences());

            overallLogOut.println("Stop criterion " + stopCriterion);
            covDef.printResultToLog(overallLogOut);
            overallLogOut.close();
        }

        //print timing information
        long elapsedTime = System.currentTimeMillis() - time;
        double minutes = (double) elapsedTime / (double) 1000 / (double) 60;
        System.out.println("Selection took " + minutes + " minutes(" + elapsedTime + " milliseconds)");
        logOut.println("Selection took " + minutes + " minutes (" + elapsedTime + " milliseconds)");
        logOut.flush();
        logOut.close();

        wikiToDB.closeDBConnection();
        System.out.println("All done!");

    } else { // connection did not succeed
        System.out.println("\nERROR: Problems with connection to the DB, please check the mysql parameters.");
        throw new Exception("ERROR: Problems with connection to the DB, please check the mysql parameters.");
    }

}

From source file:com.autentia.intra.converter.Date2YearConverter.java

/**
 * Devuelve la representacion cadena de una fecha
 *//*w ww  . j ava  2s .c om*/
public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException {
    DateFormat fmt = new SimpleDateFormat("yyyy");
    String valor = null;
    if (value == null) {
        valor = "";
    } else {
        valor = fmt.format(value);
    }
    return valor;
}

From source file:com.recomdata.transmart.data.export.ExportDataProcessor.java

@SuppressWarnings("unused")
private String getZipFileName(String studyName) {
    StringBuilder fileName = new StringBuilder();
    DateFormat formatter = new SimpleDateFormat("MMddyyyyHHmmss");
    fileName.append(TEMP_DIR);//w ww .j a  v a2s .co  m
    fileName.append(studyName);
    fileName.append(formatter.format(Calendar.getInstance().getTime()));
    fileName.append(".zip");

    return fileName.toString();
}

From source file:hoot.services.controllers.info.ErrorLogResource.java

@GET
@Path("/export")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response exportLog() {
    ErrorLog logging = new ErrorLog();
    File out = null;/*ww  w  .  ja  v a  2s.  c  o m*/

    try {
        String outputPath = logging.generateExportLog();
        out = new File(outputPath);
        _exportLogPath = outputPath;
    } catch (Exception ex) {
        ResourceErrorHandler.handleError("Error exporting log file: " + ex.toString(),
                Status.INTERNAL_SERVER_ERROR, log);
    }
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    Date dd = new Date();
    String dtStr = dateFormat.format(dd);
    ResponseBuilder rBuild = Response.ok(out, MediaType.APPLICATION_OCTET_STREAM);
    rBuild.header("Content-Disposition", "attachment; filename=hootlog_" + dtStr + ".log");

    return rBuild.build();
}

From source file:HelloJapan.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/plain; charset=Shift_JIS");
    PrintWriter out = res.getWriter();
    res.setHeader("Content-Language", "ja");

    Locale locale = new Locale("ja", "");
    DateFormat full = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
    out.println("In Japanese:");
    out.println("\u4eca\u65e5\u306f\u4e16\u754c"); // Hello World
    out.println(full.format(new Date()));
}

From source file:com.mycompany.craftdemo.HelloJob.java

public void execute(JobExecutionContext context) throws JobExecutionException {

    DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    Date date = new Date();
    System.out.println(dateFormat.format(date));

    try {/*ww w .ja  v a2  s. com*/
        // unschedule the job if market is closed
        if (!utility.isValidTime()) {
            System.out.println("Stock market is closed. exiting... Will Get back tommorow at 9.30 AM EST");
            utility.schedulerShutdown();
        } else {
            System.out.println("Application has been started. Checking current prices");

            //getting configurations
            String filePath = utility.getFilePath();
            JSONObject config = utility.getConfig(filePath);

            //getting stock api data
            JSONObject apiData = utility.getAPIData((String) config.get("apiURL"));
            Double currentPrice = (double) apiData.get("LastPrice");
            System.out.println("Current Price " + currentPrice);

            //calculates the profit
            double newProfit = utility.getProfit(currentPrice, (long) config.get("buyPrice"));

            //if min profit is acheived then it unschedule the job for the day
            if (newProfit >= (long) config.get("minProfit")) {
                utility.send((long) config.get("phNo"), currentPrice, newProfit, (String) config.get("domain"),
                        (String) config.get("companyName"));
                System.out.println(
                        "Threshold profit achieved. exiting for now. Service will start next on next business day at 9.30 EST");
                utility.schedulerShutdown();
            } else {
                //if stock prices are going down or constant , wait time will be incresed to 2 times| starts with 15 min
                if (childScheduler.lastPrice >= currentPrice) {
                    if (childScheduler.waitTime < 60)
                        childScheduler.waitTime = childScheduler.waitTime == 0 ? 15
                                : childScheduler.waitTime * 2;
                    System.out.println("Cannot make any profit at this time. Will check again after"
                            + childScheduler.waitTime + " mins");
                    utility.rescheduleJob();
                } else {
                    childScheduler.waitTime = 0;
                    System.out.println("Cannot make any profit at this time. Will check again after 15 mins");
                }
                childScheduler.lastPrice = currentPrice;

            }
        }
    } catch (NullPointerException e) {
        throw new RuntimeException(e);
    }

}