Example usage for java.text DateFormat getInstance

List of usage examples for java.text DateFormat getInstance

Introduction

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

Prototype

public static final DateFormat getInstance() 

Source Link

Document

Get a default date/time formatter that uses the SHORT style for both the date and the time.

Usage

From source file:Main.java

private static void setEndOfWeekToCalendar(Calendar c) {
    // Get First Day of next week so it will be considered until 0 hrs of
    // next week//w  w w  .j a  va 2s  .  c  om
    c.set(Calendar.DAY_OF_WEEK, c.getMaximum(Calendar.DAY_OF_WEEK));
    setEndOfDayToCalendar(c);
    Log.d("La Cuenta: ", "Max of Current Week: " + DateFormat.getInstance().format(c.getTime()));
}

From source file:Main.java

private static void setEndOfMonthToCalendar(Calendar c) {
    // Get the First Day of next month so it will e considered until 0 hours
    // of next month
    int max = c.getMaximum(Calendar.DAY_OF_MONTH);
    c.set(Calendar.DAY_OF_MONTH, max);
    setEndOfDayToCalendar(c);//  www. j  a  va2  s  . c o  m
    Log.d("La Cuenta: ", "Max of Current Month: " + DateFormat.getInstance().format(c.getTime()));
}

From source file:org.clever.Common.Storage.VirtualFileSystem.java

/**
 * This method lists contents of a file or folder
 * @param file// ww w.j a v  a2  s  .com
 * @return
 * @throws FileSystemException 
 */
public String ls(FileObject file) throws FileSystemException {
    String str = "Contents of " + file.getName() + "\n";
    if (file.exists()) {
        if (file.getType().equals(FileType.FILE)) {
            str = str + "Size: " + file.getContent().getSize() + " bytes\n" + "Last modified: "
                    + DateFormat.getInstance().format(new Date(file.getContent().getLastModifiedTime())) + "\n"
                    + "Readable: " + file.isReadable() + "\n" + "Writeable: " + file.isWriteable() + "\n";
            return str;
        } else if (file.getType().equals(FileType.FOLDER) && file.isReadable()) {
            FileObject[] children = file.getChildren();
            str = str = "Directory with " + children.length + " files \n" + "Readable: " + file.isReadable()
                    + "\n" + "Writeable: " + file.isWriteable() + "\n\n";
            //str=str+"Last modified: " +DateFormat.getInstance().format(new Date(file.getContent().getLastModifiedTime()))+"\n" ;
            for (int i = 0; i < children.length; i++) {
                str = str + children[i].getName().getBaseName() + "\n";
            }
        }
    } else {
        str = str + "The file does not exist";
    }
    return str;
}

From source file:edu.msoe.se2800.h4.Logger.java

/**
 * Example usage:/*from w ww.j a v a 2  s . co m*/
 * <p/>
 * <code>
 * public class PerfectPerson {<br/>
 * public static final String TAG = "Logger";<br/>
 * public PerfectPerson() {<br/>
 * Logger.INSTANCE.log(TAG, "My eyes are %s and my hair is %s", new String[]{"Green", "Blonde"});<br/> 
 * }<br/>
 * }<br/>
 * </code><br/>
 * will produce (PerfectPerson, My eyes are Green and my hair is Blonde).
 * 
 * @param tag of the class making the call.
 * @param message to be logged. Use %s to indicate fields.
 * @param args Strings to populate fields with. These need to be in the order they are found in
 *            the message
 */
public void log(String tag, String message, String[] args) {
    synchronized (this) {
        OutputStreamWriter writer = null;
        try {
            writer = new OutputStreamWriter(new FileOutputStream(FILE_NAME, true));
            DateFormat format = DateFormat.getInstance();

            // Print the date/timestamp
            writer.write(format.format(new Date()));
            writer.write(" | ");

            // Print the tag
            writer.write(tag);
            writer.write(" | ");

            if (StringUtils.countMatches(message, "%s") != args.length) {
                throw new IllegalArgumentException("The number of placeholders in (" + message
                        + ") was not the same as the number of args (" + args.length + ").");
            }
            for (String s : args) {
                message = StringUtils.replaceOnce(message, "%s", s);
            }

            // Print the message
            writer.write(message);
            writer.write("\n");
        } catch (FileNotFoundException e1) {
            System.out.println("The specified file could not be found.");
        } catch (IOException e) {
            System.out.println("Unable to connect to the logger. This call to log() will be ignored.");
        } finally {
            if (writer != null) {
                try {
                    Closeables.close(writer, true);
                } catch (IOException e) {
                }
            }
        }
    }

}

From source file:org.electrologic.convergence.server.cache.CacheEntry.java

@Override
public String toString() {
    StringBuilder b = new StringBuilder(50);
    DateFormat dateFormatter = DateFormat.getInstance();
    Date startDate = new Date(getStart());
    Date finishDate = new Date(getFinish());
    b.append(dateFormatter.format(startDate));
    b.append(" -> ");
    b.append(dateFormatter.format(finishDate));
    b.append(" :: [");
    b.append(getFingerprint());/*from w w w .j a v  a 2  s .co  m*/
    b.append("]");
    return b.toString();
}

From source file:uk.ac.ox.oucs.vle.ModuleImpl.java

/**
 * /*from  ww  w  .j av  a2 s  . c o m*/
 */
public void initialise() {

    Calendar calendar = new GregorianCalendar();
    calendar.set(Calendar.HOUR, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    lastMidnight = (Date) calendar.getTime();

    int aboutToCloseDays = getAboutToCloseDays();
    Calendar today = (Calendar) calendar.clone();
    today.add(Calendar.DATE, aboutToCloseDays);
    todayMidnight = (Date) today.getTime();

    int aboutToStartDays = getAboutToStartDays();
    Calendar tomorrow = (Calendar) calendar.clone();
    tomorrow.add(Calendar.DATE, aboutToStartDays);
    aboutToStart = (Date) tomorrow.getTime();

    log.info("ModuleImpl.initialise");
    log.info("Last Midnight [" + DateFormat.getInstance().format(lastMidnight) + "]");
    log.info("Today Midnight [" + DateFormat.getInstance().format(todayMidnight) + "]");
    log.info("About to Start [" + DateFormat.getInstance().format(aboutToStart) + "]");

    log.info("Courses about to Close [close date between " + DateFormat.getInstance().format(lastMidnight)
            + " and " + DateFormat.getInstance().format(todayMidnight) + "]");

    log.info("Courses about to Start [start date between " + DateFormat.getInstance().format(todayMidnight)
            + " and " + DateFormat.getInstance().format(aboutToStart) + "]");
}

From source file:com.k42b3.neodym.Http.java

public String request(int method, String url, Map<String, String> header, String body, boolean signed)
        throws Exception {
    // check cache (only GET)
    String cacheKey = url;//from   w  ww.  ja  v a  2 s . c o m

    if (method == Http.GET) {
        Cache cache = cacheManager.get(cacheKey);

        if (cache != null) {
            logger.info("Found cache for " + cacheKey + " expires in "
                    + DateFormat.getInstance().format(cache.getExpire()));

            return cache.getResponse();
        }
    }

    // build request
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 6000);
    DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);

    HttpRequestBase httpRequest;

    if (method == Http.GET) {
        httpRequest = new HttpGet(url);
    } else if (method == Http.POST) {
        httpRequest = new HttpPost(url);

        if (body != null && !body.isEmpty()) {
            ((HttpPost) httpRequest).setEntity(new StringEntity(body));
        }
    } else {
        throw new Exception("Invalid request method");
    }

    // add headers
    if (header != null) {
        Set<String> keys = header.keySet();

        for (String k : keys) {
            httpRequest.addHeader(k, header.get(k));
        }
    }

    // sign request
    if (oauth != null && signed) {
        oauth.signRequest(httpRequest);
    }

    // execute request
    logger.info("Request: " + httpRequest.getRequestLine().toString());

    HttpResponse httpResponse = httpClient.execute(httpRequest);

    logger.info("Response: " + httpResponse.getStatusLine().toString());

    HttpEntity entity = httpResponse.getEntity();
    String responseContent = EntityUtils.toString(entity);

    // log traffic
    if (trafficListener != null) {
        TrafficItem trafficItem = new TrafficItem();

        trafficItem.setRequest(httpRequest);
        trafficItem.setRequestContent(body);
        trafficItem.setResponse(httpResponse);
        trafficItem.setResponseContent(responseContent);

        trafficListener.handleRequest(trafficItem);
    }

    // check status code
    int statusCode = httpResponse.getStatusLine().getStatusCode();

    if (!(statusCode >= 200 && statusCode < 300)) {
        if (!responseContent.isEmpty()) {
            String message = responseContent.length() > 128 ? responseContent.substring(0, 128) + "..."
                    : responseContent;

            throw new Exception(message);
        } else {
            throw new Exception("No successful status code");
        }
    }

    // assign last request/response
    lastRequest = httpRequest;
    lastResponse = httpResponse;

    // cache response if expires header is set
    if (method == Http.GET) {
        Date expire = null;
        Header[] headers = httpResponse.getAllHeaders();

        for (int i = 0; i < headers.length; i++) {
            if (headers[i].getName().toLowerCase().equals("expires")) {
                try {
                    expire = DateFormat.getInstance().parse(headers[i].getValue());
                } catch (Exception e) {
                }
            }
        }

        if (expire != null && expire.compareTo(new Date()) > 0) {
            Cache cache = new Cache(cacheKey, responseContent, expire);

            cacheManager.add(cache);

            logger.info("Add to cache " + cacheKey + " expires in " + DateFormat.getInstance().format(expire));
        }
    }

    return responseContent;
}

From source file:de.perdian.commons.lang.conversion.impl.converters.StringToDateConverter.java

@Override
protected DateFormat resolveDefaultFormat(Locale locale) {
    String pattern = this.getPattern();
    if (pattern != null) {
        return new SimpleDateFormat(pattern, locale);
    } else {//  www  .  j av a  2 s . com
        Class<? extends Date> targetDateClass = this.getTargetDateClass();
        if (targetDateClass == null || targetDateClass.equals(java.util.Date.class)
                || targetDateClass.equals(java.sql.Date.class)) {
            return DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
        } else if (targetDateClass.equals(java.sql.Timestamp.class)) {
            return DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale);
        } else if (targetDateClass.equals(java.sql.Time.class)) {
            return DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
        } else {
            return DateFormat.getInstance();
        }
    }
}

From source file:org.jfree.chart.demo.TimePeriodValuesDemo3.java

/**
 * Creates a dataset, consisting of two series of monthly data.
 *
 * @return the dataset./* w w  w .ja  v  a 2  s.  co  m*/
 */
public XYDataset createDataset() {

    final TimePeriodValues s1 = new TimePeriodValues("Series 1");

    final DateFormat df = DateFormat.getInstance();
    try {
        final Date d0 = df.parse("11/5/2003 0:00:00.000");
        final Date d1 = df.parse("11/5/2003 0:15:00.000");
        final Date d2 = df.parse("11/5/2003 0:30:00.000");
        final Date d3 = df.parse("11/5/2003 0:45:00.000");
        final Date d4 = df.parse("11/5/2003 1:00:00.001");
        final Date d5 = df.parse("11/5/2003 1:14:59.999");
        final Date d6 = df.parse("11/5/2003 1:30:00.000");
        final Date d7 = df.parse("11/5/2003 1:45:00.000");
        final Date d8 = df.parse("11/5/2003 2:00:00.000");
        final Date d9 = df.parse("11/5/2003 2:15:00.000");

        s1.add(new SimpleTimePeriod(d0, d1), 0.39);
        //s1.add(new SimpleTimePeriod(d1, d2), 0.338);
        s1.add(new SimpleTimePeriod(d2, d3), 0.225);
        s1.add(new SimpleTimePeriod(d3, d4), 0.235);
        s1.add(new SimpleTimePeriod(d4, d5), 0.238);
        s1.add(new SimpleTimePeriod(d5, d6), 0.236);
        s1.add(new SimpleTimePeriod(d6, d7), 0.25);
        s1.add(new SimpleTimePeriod(d7, d8), 0.238);
        s1.add(new SimpleTimePeriod(d8, d9), 0.215);
    } catch (Exception e) {
        System.out.println(e.toString());
    }

    final TimePeriodValuesCollection dataset = new TimePeriodValuesCollection();
    dataset.addSeries(s1);
    dataset.setDomainIsPointsInTime(false);

    return dataset;

}

From source file:org.apromore.tools.cpfimporter.Import.java

private static void uploadProcess(final File file, final File toFile) {
    try {/*from w  w  w .  j  a va 2s  .  c  o  m*/
        final String userName = "admin";
        final Set<RequestParameterType<?>> noCanoniserParameters = Collections.emptySet();

        File parentFile = toFile.getParentFile();
        String ext = FilenameUtils.getExtension(toFile.getName());
        if (getNativeFormat(ext) != null && parentFile != null) {
            createFolder(parentFile);
            int parentId = getFolderId(parentFile);
            assert parentId != -1;

            String now = DateFormat.getInstance().format(new Date());

            if (manager == null) {
                LOGGER.error("Failed to load file {} because no -manager parameter was specified");
            } else {
                manager.importProcess(userName, // user name
                        parentId, // folder ID
                        getNativeFormat(ext), // native type
                        FilenameUtils.getBaseName(toFile.getName()), // process name
                        "1.0", // version number
                        new FileInputStream(file), // XML serialization of the process
                        "domain", "documentation", now, // creation timestamp
                        now, // last modification timestamp
                        true, // make public?
                        noCanoniserParameters);
            }
        }
    } catch (Exception e) {
        LOGGER.error("Failed to load file {} due to {}", file.getName(), e.getMessage());
    }
}