Java Code Examples for java.text.SimpleDateFormat#getDateTimeInstance()

The following examples show how to use java.text.SimpleDateFormat#getDateTimeInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GenericExportWorker.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
public void setDateAndDecimalLocale(Locale dateAndDecimalLocale) {
	dateFormat = SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT, dateAndDecimalLocale);
	dateTimeFormat = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.MEDIUM, dateAndDecimalLocale);
	((SimpleDateFormat) dateTimeFormat).applyPattern(((SimpleDateFormat) dateTimeFormat).toPattern().replaceFirst("y+", "yyyy").replaceFirst(", ", " "));
	dateFormatter = null;
	dateTimeFormatter = null;
	decimalFormat = DecimalFormat.getNumberInstance(dateAndDecimalLocale);
	decimalFormat.setGroupingUsed(false);
}
 
Example 2
Source File: MessageListItemAdapter.java    From Sparkplug with Eclipse Public License 1.0 5 votes vote down vote up
@NonNull
@Override
public View getView(final int position, View convertView, @NonNull ViewGroup parent){
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.message_list_item, parent, false);

    // Set up the topic tokens
    TextView topicTextView = (TextView) rowView.findViewById(R.id.message_topic_text);
    String[] topicTokens = messages.get(position).getTopic().split("/");
    if (messages.get(position).getMessageType() == MessageType.Published) {
        topicTextView.setText(topicTokens[1] + " :: " + topicTokens[3] + " :: Published");
    } else if (messages.get(position).getMessageType() == MessageType.Received) {
        topicTextView.setText(topicTokens[1] + " :: " + topicTokens[3] + " :: Received");
    }


    // Set up the payload
    try {
        PayloadDecoder<SparkplugBPayload> decoder = new SparkplugBPayloadDecoder();
        SparkplugBPayload incomingPayload = decoder.buildFromByteArray(messages.get(position).getMessage().getPayload());

        TextView payloadTextView = (TextView) rowView.findViewById(R.id.message_payload_text);

        StringBuilder sb = new StringBuilder();
        for (Metric metric : incomingPayload.getMetrics()) {
            sb.append(metric.getName()).append("=").append(metric.getValue()).append("   ");
        }

        payloadTextView.setText(sb.toString());
    } catch (Exception e) {
        Log.d(TAG, "Failed to parse out payload", e);
    }

    TextView dateTextView = (TextView) rowView.findViewById(R.id.message_date_text);
    DateFormat dateTimeFormatter = SimpleDateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM);
    String shortDateStamp = dateTimeFormatter.format(messages.get(position).getTimestamp());
    dateTextView.setText(context.getString(R.string.message_time_fmt, shortDateStamp));

    return rowView;
}
 
Example 3
Source File: Connection.java    From Sparkplug with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Add an action to the history of the client
 * @param action the history item to add
 */
public void addAction(String action) {

    Object[] args = new String[1];
    DateFormat dateTimeFormatter = SimpleDateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
    args[0] = dateTimeFormatter.format(new Date());

    String timestamp = context.getString(R.string.timestamp, args);
    history.add(action + timestamp);

    notifyListeners(new PropertyChangeEvent(this, ActivityConstants.historyProperty, null, null));
}
 
Example 4
Source File: StringUtil.java    From LittleFreshWeather with Apache License 2.0 5 votes vote down vote up
public static String getCurrentDateTime(String pattern) {
    GregorianCalendar currentCalendar = new GregorianCalendar();
    SimpleDateFormat simpleDateFormat = (SimpleDateFormat)SimpleDateFormat.getDateTimeInstance();
    simpleDateFormat.applyPattern(pattern);

    return simpleDateFormat.format(currentCalendar.getTime());
}
 
Example 5
Source File: DateFormatManager.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private synchronized void configure() {
  _dateFormat = SimpleDateFormat.getDateTimeInstance(DateFormat.FULL,
      DateFormat.FULL,
      getLocale());
  _dateFormat.setTimeZone(getTimeZone());

  if (_pattern != null) {
    ((SimpleDateFormat) _dateFormat).applyPattern(_pattern);
  }
}
 
Example 6
Source File: TracksActivity.java    From android_maplibui with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void getStats() {
    ContentResolver resolver = getContentResolver();
    String sort = TrackLayer.FIELD_TIMESTAMP + " ASC";
    Cursor points = resolver.query(mContentUriTrackPoints, null, null, null, sort);
    int total = 0, sent = 0;
    DateFormat df = SimpleDateFormat.getDateTimeInstance();
    String last = "-";
    if (points != null) {
        total = points.getCount();
        if (points.moveToLast()) {
            int id = points.getColumnIndex(TrackLayer.FIELD_TIMESTAMP);
            long lastL = points.getLong(id);
            last = df.format(new Date(lastL));
        }
        points.close();
    }

    String selection = TrackLayer.FIELD_SENT + " = 1";
    points = resolver.query(mContentUriTrackPoints, null, selection, null, sort);
    if (points != null) {
        sent = points.getCount();
        points.close();
    }

    if (mProgress != null)
        mProgress.dismiss();

    AlertDialog builder = new AlertDialog.Builder(this)
            .setTitle(R.string.stats)
            .setMessage(getString(R.string.trackpoints_stats, total, sent, last))
            .setPositiveButton(R.string.ok, null).create();
    builder.show();
}
 
Example 7
Source File: DefaultUserDateFormatter.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getShortFormat(final long milliseconds, final boolean natural) {
    if(-1 == milliseconds) {
        return LocaleFactory.localizedString("Unknown");
    }
    final DateFormat format = SimpleDateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
    format.setTimeZone(TimeZone.getTimeZone(tz));
    return format.format(milliseconds);
}
 
Example 8
Source File: Network.java    From KJFrameForAndroid with Apache License 2.0 5 votes vote down vote up
/**
 * 标记Respondeader响应头在Cache中的tag
 *
 * @param headers
 * @param entry
 */
private void addCacheHeaders(Map<String, String> headers, Cache.Entry entry) {
    if (entry == null) {
        return;
    }
    if (entry.etag != null) {
        headers.put("If-None-Match", entry.etag);
    }
    if (entry.serverDate > 0) {
        Date refTime = new Date(entry.serverDate);
        DateFormat sdf = SimpleDateFormat.getDateTimeInstance();
        headers.put("If-Modified-Since", sdf.format(refTime));

    }
}
 
Example 9
Source File: JmxDumpUtil.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Show a message stating the JmxDumper has been started, with the current date and time. 
 */
private static void showStartBanner(PrintWriter out)
{
    DateFormat df = SimpleDateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
    out.println(JmxDumpUtil.class.getSimpleName() + " started: " + df.format(new Date()));
    out.println();
}
 
Example 10
Source File: DateUtils.java    From boon with Apache License 2.0 5 votes vote down vote up
public static String getGMTString(Date date) {

        /*
        * To SL: Now I know what you mean work everywhere. :)
        * We format our dates differently here.
        * DAY/MONTH/YEAR although logical and done everywhere. :)
        * --RMH
        */
        DateFormat df =  SimpleDateFormat.getDateTimeInstance( DateFormat.SHORT,
                DateFormat.SHORT, Locale.FRANCE );
        df.setTimeZone(TimeZone.getTimeZone("GMT"));
        return df.format(date);
	}
 
Example 11
Source File: Network.java    From styT with Apache License 2.0 5 votes vote down vote up
/**
 * 标记Respondeader响应头在Cache中的tag
 */
private void addCacheHeaders(ArrayList<HttpParamsEntry> headers, ICache.Entry entry) {
    if (entry == null) {
        return;
    }
    if (entry.etag != null) {
        headers.add(new HttpParamsEntry("If-None-Match", entry.etag));
    }
    if (entry.serverDate > 0) {
        Date refTime = new Date(entry.serverDate);
        DateFormat sdf = SimpleDateFormat.getDateTimeInstance();
        headers.add(new HttpParamsEntry("If-Modified-Since", sdf.format(refTime)));

    }
}
 
Example 12
Source File: ExportWizardAction.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private void writeExportChangeLog(ExportPredef oldExport, ExportPredef newExport, ComAdmin admin) {
	DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, admin.getLocale());

	StringBuilder descriptionSb = new StringBuilder();
	descriptionSb.append(addChangedFieldLog("shortname", newExport.getShortname(), oldExport.getShortname()))
		.append(addChangedFieldLog("description", newExport.getDescription(), oldExport.getDescription()))
		.append(addChangedFieldLog("mailing list", newExport.getMailinglistID(), oldExport.getMailinglistID()))
		.append(addChangedFieldLog("target group", newExport.getTargetID(), oldExport.getTargetID()))
		.append(addChangedFieldLog("recipient type", newExport.getUserType(), oldExport.getUserType()))
		.append(addChangedFieldLog("recipient status", newExport.getUserStatus(),oldExport.getUserStatus()))
		.append(addChangedFieldLog("columns", newExport.getColumns(), oldExport.getColumns()))
		.append(addChangedFieldLog("mailing lists", newExport.getMailinglists(), oldExport.getMailinglists()))
		.append(addChangedFieldLog("separator", newExport.getSeparator(), oldExport.getSeparator()))
		.append(addChangedFieldLog("delimiter", newExport.getDelimiter(), oldExport.getDelimiter()))
		.append(addChangedFieldLog("charset", newExport.getCharset(), oldExport.getCharset()))
		.append(addChangedFieldLog("change period start", newExport.getTimestampStart(), oldExport.getTimestampStart(), dateFormat))
		.append(addChangedFieldLog("change period end", newExport.getTimestampEnd(), oldExport.getTimestampEnd(), dateFormat))
		.append(addChangedFieldLog("change period last days", newExport.getTimestampLastDays(), oldExport.getTimestampLastDays()))
		.append(addChangedFieldLog("creation period start", newExport.getCreationDateStart(), oldExport.getCreationDateStart(), dateFormat))
		.append(addChangedFieldLog("creation period end", newExport.getCreationDateEnd(), oldExport.getCreationDateEnd(), dateFormat))
		.append(addChangedFieldLog("creation period last days", newExport.getCreationDateLastDays(), oldExport.getCreationDateLastDays()))
		.append(addChangedFieldLog("ML binding period start", newExport.getMailinglistBindStart(), oldExport.getMailinglistBindStart(), dateFormat))
		.append(addChangedFieldLog("ML binding period end", newExport.getMailinglistBindEnd(), oldExport.getMailinglistBindEnd(), dateFormat))
		.append(addChangedFieldLog("ML binding period last days", newExport.getMailinglistBindLastDays(), oldExport.getMailinglistBindLastDays()));

	if (StringUtils.isNotBlank(descriptionSb.toString())) {
		descriptionSb.insert(0, ". ");
		descriptionSb.insert(0, getExportDescription(oldExport));

		writeUserActivityLog(admin, "edit export", descriptionSb.toString());
	}
}
 
Example 13
Source File: Helper.java    From FairEmail with GNU General Public License v3.0 4 votes vote down vote up
static DateFormat getDateTimeInstance(Context context, int dateStyle, int timeStyle) {
    // TODO fix time format
    return SimpleDateFormat.getDateTimeInstance(dateStyle, timeStyle);
}
 
Example 14
Source File: MainActivity.java    From NaturalDateFormat with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView tv = (TextView) findViewById(R.id.text);
    Date now = new Date();
    Random random = new Random();
    long year2 = 1000L * 60 * 60 * 24 * 365 * 2;
    long hour3 = 1000L * 60 * 60 * 3;
    long month = 1000L * 60 * 60 * 24 * 30;
    StringBuffer buffer = new StringBuffer();
    DateFormat format = SimpleDateFormat.getDateTimeInstance();
    long[] mod = new long[]{
            year2,
            hour3,
            year2,
            month
    };
    NaturalDateFormat[] formats = new NaturalDateFormat[]{
            new RelativeDateFormat(this, NaturalDateFormat.DATE),
            new RelativeDateFormat(this, NaturalDateFormat.TIME),
            new AbsoluteDateFormat(this, NaturalDateFormat.WEEKDAY | NaturalDateFormat.DATE),
            new AbsoluteDateFormat(this, NaturalDateFormat.DATE | NaturalDateFormat.HOURS | NaturalDateFormat.MINUTES)
    };

    ((AbsoluteDateFormat)formats[2]).setAbbreviated(true);
    ((AbsoluteDateFormat)formats[3]).setTwelveHour(true);

    for (int j = 0; j < formats.length; j++) {
        for (int i = 0; i < 5; i++) {
            Date date = new Date(now.getTime() + random.nextLong() % mod[j]);
            buffer.append(format.format(date)).
                    append("  -  ").
                    append(formats[j].format(date.getTime())).
                    append("\n");
        }
        buffer.append("\n");
    }
    tv.setText(buffer.toString());
}
 
Example 15
Source File: MailingServiceImpl.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
@Transactional
@Validate("sendMailing")
public MaildropEntry addMaildropEntry(MailingModel model, List<UserAction> userActions) throws Exception {
	if (!DateUtil.isValidSendDate(model.getSendDate())) {
		throw new SendDateNotInFutureException();
	}
	
       Calendar now = Calendar.getInstance();
       
	Mailing mailing = getMailing(model);
	
	if (model.getMaildropStatus() == MaildropStatus.WORLD && maildropService.isActiveMailing(mailing.getId(), mailing.getCompanyID())) {
		throw new WorldMailingAlreadySentException();
	}

	MaildropEntry maildrop = new MaildropEntryImpl();

	maildrop.setStatus(model.getMaildropStatus().getCode());
	maildrop.setMailingID(model.getMailingId());
	maildrop.setCompanyID(model.getCompanyId());
       maildrop.setStepping(model.getStepping());
	maildrop.setBlocksize(model.getBlocksize());

	maildrop.setSendDate(model.getSendDate());
	
	Calendar tmpGen = Calendar.getInstance();
       tmpGen.setTime(model.getSendDate());
       tmpGen.add(Calendar.MINUTE, -this.getMailGenerationMinutes(model.getCompanyId()));
       if(tmpGen.before(now)) {
           tmpGen=now;
       }
       maildrop.setGenDate(tmpGen.getTime());
	maildrop.setGenChangeDate(now.getTime());
	
	if( model.getMaildropStatus() == MaildropStatus.WORLD) {
		maildrop.setGenStatus(DateUtil.isDateForImmediateGeneration(maildrop.getGenDate()) ? 1 : 0);
	} else if( model.getMaildropStatus() == MaildropStatus.TEST || model.getMaildropStatus() == MaildropStatus.ADMIN) {
		maildrop.setGenStatus( 1);
	}

       mailing.getMaildropStatus().add(maildrop);

       mailingDao.saveMailing(mailing, false);
       if (logger.isInfoEnabled()) {
       	logger.info("send mailing id: " + mailing.getId() + " type: "+maildrop.getStatus());
       }

       SimpleDateFormat dateTimeFormat = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.UK);
       dateTimeFormat.applyPattern(dateTimeFormat.toPattern().replaceFirst("y+", "yyyy").replaceFirst(", ", " "));
	String strDate = dateTimeFormat.format(model.getSendDate());
	String description = String.format("Date: %s. Mailing %s(%d) %s", strDate, mailing.getShortname(), mailing.getId(), "normal");

       userActions.add(new UserAction("edit send date", description));

       return maildrop;
}
 
Example 16
Source File: DateTimeConverter.java    From octoandroid with GNU General Public License v3.0 4 votes vote down vote up
public static String msTimeToDateTimeString(long msTime) {
    Date date = new Date(msTime);
    DateFormat df = SimpleDateFormat.getDateTimeInstance();
    return df.format(date);
}
 
Example 17
Source File: ShareProofActivity.java    From proofmode with GNU General Public License v3.0 4 votes vote down vote up
private void generateProofOutput (File fileMedia, Date lastModified, File fileMediaSig, File fileMediaProof, File fileMediaProofSig, String hash, boolean shareMedia, PrintWriter fBatchProofOut, ArrayList<Uri> shareUris, StringBuffer sb)
{
    DateFormat sdf = SimpleDateFormat.getDateTimeInstance();

    String fingerprint = PgpUtils.getInstance(this).getPublicKeyFingerprint();

    sb.append(fileMedia.getName()).append(' ');
    sb.append(getString(R.string.last_modified)).append(' ').append(sdf.format(lastModified));
    sb.append(' ');
    sb.append(getString(R.string.has_hash)).append(' ').append(hash);
    sb.append("\n\n");
    sb.append(getString(R.string.proof_signed) + fingerprint);
    sb.append("\n");
    sb.append(getString(R.string.view_public_key) + fingerprint);
    sb.append("\n\n");

    /**
     * //disable for now
    try {
        final TimeBeatNotarizationProvider tbNotarize = new TimeBeatNotarizationProvider(this);
        String tbProof = tbNotarize.getProof(hash);
        sb.append(getString(R.string.independent_notary) + ' ' + tbProof);
    }
    catch (Exception ioe)
    {
        Timber.e("Error checking for Timebeat proof",ioe);
    }**/

    shareUris.add(FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider",fileMediaProof));

    if (shareMedia) {
        shareUris.add(FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider",fileMedia));
        shareUris.add(FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider",fileMediaSig));
        shareUris.add(FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider",fileMediaProofSig));
    }

    if (fBatchProofOut != null)
    {
        try {
            BufferedReader br = new BufferedReader(new FileReader(fileMediaProof));
            br.readLine();//skip header
            String csvLine = br.readLine();
            // Log.i("ShareProof","batching csv line: " + csvLine);
            fBatchProofOut.println(csvLine);
            br.close();
        }
        catch (IOException ioe)
        {}
    }
}
 
Example 18
Source File: DeviceAdminReceiver.java    From android-testdpc with Apache License 2.0 4 votes vote down vote up
@TargetApi(VERSION_CODES.O)
// @Override
public void onPasswordFailed(Context context, Intent intent, UserHandle user) {
    if (!Process.myUserHandle().equals(user)) {
        // This password failure was on another user, for example a parent profile. Ignore it.
        return;
    }
    DevicePolicyManager devicePolicyManager = (DevicePolicyManager) context.getSystemService(
            Context.DEVICE_POLICY_SERVICE);
    /*
     * Post a notification to show:
     *  - how many wrong passwords have been entered;
     *  - how many wrong passwords need to be entered for the device to be wiped.
     */
    int attempts = devicePolicyManager.getCurrentFailedPasswordAttempts();
    int maxAttempts = devicePolicyManager.getMaximumFailedPasswordsForWipe(null);

    String title = context.getResources().getQuantityString(
            R.plurals.password_failed_attempts_title, attempts, attempts);

    ArrayList<Date> previousFailedAttempts = getFailedPasswordAttempts(context);
    Date date = new Date();
    previousFailedAttempts.add(date);
    Collections.sort(previousFailedAttempts, Collections.<Date>reverseOrder());
    try {
        saveFailedPasswordAttempts(context, previousFailedAttempts);
    } catch (IOException e) {
        Log.e(TAG, "Unable to save failed password attempts", e);
    }

    String content = maxAttempts == 0
            ? context.getString(R.string.password_failed_no_limit_set)
            : context.getResources().getQuantityString(
                    R.plurals.password_failed_attempts_content, maxAttempts, maxAttempts);

    NotificationCompat.Builder warn = NotificationUtil.getNotificationBuilder(context);
    warn.setSmallIcon(R.drawable.ic_launcher)
            .setTicker(title)
            .setContentTitle(title)
            .setContentText(content)
            .setContentIntent(PendingIntent.getActivity(context, /* requestCode */ -1,
                    new Intent(DevicePolicyManager.ACTION_SET_NEW_PASSWORD), /* flags */ 0));

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    inboxStyle.setBigContentTitle(title);

    final DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance();
    for(Date d : previousFailedAttempts) {
        inboxStyle.addLine(dateFormat.format(d));
    }
    warn.setStyle(inboxStyle);

    NotificationManager nm = (NotificationManager)
            context.getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(PASSWORD_FAILED_NOTIFICATION_ID, warn.build());
}
 
Example 19
Source File: DateUtilities.java    From openemm with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * Get locale-dependent timezone-aware date/time format using predefined notations (see {@link DateFormat#FULL},
 * {@link DateFormat#LONG}, {@link DateFormat#MEDIUM}, {@link DateFormat#SHORT} and {@link DateFormat#DEFAULT}).
 *
 * @param dateStyle the given date formatting style.
 * @param timeStyle the given time formatting style.
 * @param locale a locale to be used to produce locale-dependent date format.
 * @param timezone a timezone to be assigned to date format object.
 * @return a locale-dependent timezone-aware date format object.
 */
public static SimpleDateFormat getDateTimeFormat(int dateStyle, int timeStyle, Locale locale, TimeZone timezone) {
	SimpleDateFormat format = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance(dateStyle, timeStyle, locale);
	format.applyPattern(format.toPattern().replaceFirst("y+", "yyyy").replaceFirst(", ", " "));
	format.setTimeZone(timezone);
	return format;
}
 
Example 20
Source File: DateUtilities.java    From openemm with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * Get locale-dependent date/time format pattern using predefined notations (see {@link DateFormat#FULL},
 * {@link DateFormat#LONG}, {@link DateFormat#MEDIUM}, {@link DateFormat#SHORT} and {@link DateFormat#DEFAULT}).
 *
 * @param dateStyle the given date formatting style.
 * @param timeStyle the given time formatting style.
 * @param locale a locale to be used to produce locale-dependent date format.
 * @return a locale-dependent date format pattern string.
 */
public static String getDateTimeFormatPattern(int dateStyle, int timeStyle, Locale locale) {
	SimpleDateFormat format = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance(dateStyle, timeStyle, locale);
	return format.toPattern();
}