My requirements:
ddmm + 2numbers
dd - day
mm - month
number - id number
Examples of my output
Today - 031201, 031202, 031203 ...
Tommorrow - 041201
Properties file: (idNumber.properties)
idNumber = 1;
Here is the java code I did:
public class Test{
public static void main(String[] args)
{
Test test = new Test();
test.generate();
}
public String generate()
{
DateFormat dateFormat = new SimpleDateFormat("ddMM");
Date date = new Date();
String currentDate = dateFormat.format(date);
String idNumber = generateIdNumber();
String complete = currentDate + idNumber;
return complete;
}
public String generateIdNumber(){
Properties idNoProp = new Properties();
InputStream idNoInput = new FileInputStream("idNumber.properties"); //java properties file
idNoProp.load(idNoInput);
String idNumber = idNoProp.getProperty("idNumber");
int idNo = Integer.valueOf(idNumber);
String result = "";
if (idNo < 10) {
result = "0" + idNo;
} else {
result = "" + idNo;
}
idNo++;
OutputStream output = new FileOutputStream("idNumber.properties");
idNoProp.setProperty("idNumber", "" + idNo);
idNoProp.store(output, null);
return result;
}
}
My question is how do I reset the tommorrow id number start from 01?
You can add a property LAST_VISIT to your properties file. When you want to save the properties file, set the current date to it. In this way
DateFormat dateFormat = new SimpleDateFormat("ddMM");
Date date = new Date();
String currentDate = dateFormat.format(date);
idNoProp.setProperty("LAST_VISIT", currentDate);
Now in generateIdNumber() first check the value of LAST_VISIT. If it dose not equal currentDate , you must reset idNo. It works for everyday and every tommorow.
Try to put a class static field to remember last used date for ids. Whenever you are in the next date relatively to the field you'll reset your idNo and update the last used date field (sorry for spelling)
You can store a Map<String,Integer> that would hold the last index for each String representation of date. This way, each date would have its own indices starting with 1.
You can run a scheduler which will reset the idNo at the start of each day, like at 00 hours. This will always gives you the consistent result, as if sometimes server/program restarts, it will not lead to any duplicate result.
if you want format a number with two number, example '01' you could do this:
String.format("%02d", Integer.valueOf(idNumber));
instead of:
int idNo = Integer.valueOf(idNumber);
String result = "";
if (idNo < 10) {
result = "0" + idNo;
} else {
result = "" + idNo;
}
public class Test{
public static void main(String[] args) throws IOException
{
Test test = new Test();
System.out.println(""+test.generate());
}
public String generate() throws IOException
{
DateFormat dateFormat = new SimpleDateFormat("ddMM");
Date date = new Date();
String currentDate = dateFormat.format(date);
String idNumber = generateIdNumber(currentDate);
String complete = currentDate + idNumber;
return complete;
}
public String generateIdNumber(String currentDate) throws IOException{
Properties idNoProp = new Properties();
InputStream idNoInput = new FileInputStream("idNumber.properties"); //java properties file
idNoProp.load(idNoInput);
String idNumber = idNoProp.getProperty("idNumber");
int idNo = Integer.valueOf(idNumber);
String strOnlyDay = currentDate.substring(0, 2);
System.out.println(strOnlyDay);// will return the first two characters of the day
String result = "";
if (idNo < 10) {
result = "0" + idNo;
} else {
result = "" + idNo;
}
idNo++;
OutputStream output = new FileOutputStream("idNumber.properties");
if (strOnlyDay.equals("01")){
idNo = 1;
}
idNoProp.setProperty("idNumber", "" + idNo);
idNoProp.store(output, null);
return result;
}
}
Try to pass the value of your current date into generateIdNumber than see the code. I hope this will help. Hoping you will preserve the value of idNo.
Related
I want to set text by date and incrementing loop, and when the day changes looping start from the beginning.
Example
1. day 1 =
a. nameFile 110920190001
b. nameFile 110920190002, etc.
2. day 2 =
a. nameFile 120920190001
b. nameFile 120920190002, etc.
Code
Date documentsDate = Calendar.getInstance().getTime();
SimpleDateFormat documentDates = new SimpleDateFormat("ddMMyy");
String setTitleDocument = documentDates.format(documentsDate);
for(int i = 1; i <= 1000; i++) {
String countDocument = String.format("%04d", i);
textNameDocument.setText("Document " + setTitleDocument + countDocument);
}
Just put the Date Initialization in the for loop for it to always take the new Instance of the date.
public static void replace(String s) {
for (int i = 1; i <= 1000; i++) {
Date documentsDate = Calendar.getInstance().getTime();
SimpleDateFormat documentDates = new SimpleDateFormat("ddMMyy");
String setTitleDocument = documentDates.format(documentsDate);
String countDocument = String.format("%04d", i);
textNameDocument.setText("Document " + setTitleDocument + countDocument);
}
}
This question already has answers here:
How to compare dates in Java? [duplicate]
(11 answers)
Closed 5 years ago.
I'm trying to write 'isPast(String dateStr)' function, which receives date string and returns true if it's in the past and false otherwise.
private static boolean isPast(String dateStr) {
Calendar c = GregorianCalendar.getInstance();
int currentYear = c.get(Calendar.YEAR);
int currentMonth = c.get(Calendar.MONTH);
int currentDay = c.get(Calendar.DAY_OF_MONTH);
int currentHour = c.get(Calendar.HOUR_OF_DAY);
int currentMinute = c.get(Calendar.MINUTE);
c.set(currentYear, currentMonth, currentDay, currentHour, currentMinute);
Date now = c.getTime();
SimpleDateFormat sdfDates = new SimpleDateFormat("dd/m/yyyy");
Date date = null;
try {
date = sdfDates.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
if (now.compareTo(date) == 1){
System.out.println(dateStr + " date given is past");
return true;
}
System.out.println(dateStr + " date given is future");
return false;
}
And i'm calling it with:
String str1 = "22/04/2018";
String str2 = "22/01/2018";
System.out.println(isPast(str1));
System.out.println(isPast(str2));
And the output is:
22/04/2018 date given is past
22/01/2018 date given is past
What is going on here? It's not true. I'm on this for too long - it should be simple, obviously i'm missing something with that Calendar object...
Use LocalDate that is available in Java 8
public static void main(String[] args) {
String str1 = "22/04/2018";
String str2 = "22/01/2018";
System.out.println(isPast(str1));
System.out.println(isPast(str2));
}
private static boolean isPast(String dateStr) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate dates = LocalDate.parse(dateStr, formatter);
return dates.isBefore(LocalDate.now());
}
Try this:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
private static final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
public static void main(String[] args) {
String str1 = "22/04/2018";
String str2 = "22/01/2018";
String str3 = "xx/01/2018";
Date now = new Date();
testDate (str1, now);
testDate (str2, now);
testDate (str3, now);
}
private static void testDate(String str, Date now) {
try {
if (sdf.parse(str).before(now)) {
System.out.println(str + " is in the past.");
} else {
System.out.println(str + " is in the future.");
}
} catch (ParseException e) {
System.out.println("Date not in format dd/MM/yyyy : " + str);
}
}
}
Output:
22/04/2018 is in the future.
22/01/2018 is in the past.
Date not in format dd/MM/yyyy : xx/01/2018
If you have to use Calendar, try this:
private static void testDateUsingCalendar (String str, Date now) {
try {
String[] split = str.split("/");
Calendar c = GregorianCalendar.getInstance();
c.set(Integer.valueOf(split[2]), Integer.valueOf(split[1]), Integer.valueOf(split[0]));
if (c.getTime().before(now)) {
System.out.println(str + " is in the past.");
} else {
System.out.println(str + " is in the future.");
}
} catch (Exception e) {
System.out.println("Date not in format dd/MM/yyyy : " + str);
}
}
Is there a way to add number of days to a date using java Date apis, vs hitting the database?
The date input is off format: yyyy-MM-dd, MM/dd/yyyy
Here is my current code:
public String AddToDate(String holdDate, int holdDays)
{
try
{
Database db = new Database();
String sQuery = "SELECT DATEADD(dd,?,?) AS NewDate";
Object[] param = new Object[2];
param[0] = holdDays;
param[1] = holdDate;
db.queryPS(sQuery, param);
if ( db.getRow() )
{
return db.getField("NewDate");
}
else
return "";
}
catch(Exception ex)
{
return "";
}
}
I have not tested this, but this is what I have so far:
public String AddToDate(String holdDate, int holdDays)
{
try
{
String newDate = "";
SimpleDateFormat inFormatter = new SimpleDateFormat("MM/dd/yyyy");
Date date1 = inFormatter.parse(holdDate);
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
cal.add(Calendar.DATE, holdDays); // number of days to add
newDate = (inFormatter.format(cal.getTime()));
return newDate;
}
catch(Exception ex)
{
ex.printStackTrace();
return "";
}
}
Used the below code and not getting the exact output.
Desired output:
2015-09-04T11:30:06-0500 to 2015-09-04T11:30:06-05:00
Actual output:
dateValue => 2015-10-19T16:52:23-0400
a => 2015-10-20T02:22:23+0530
My code:
public class test {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = formattedDate("2015-10-19T16:52:23-0400");
System.out.println ("a => " + a);
}
public static String formattedDate (String dateValue) {
String expectedFormat = "";
SimpleDateFormat inputDateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
SimpleDateFormat outputDateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZ");
try {
System.out.println("dateValue => " + dateValue);
if (dateValue == null || dateValue.isEmpty()) {
dateValue = "";
}
inputDateFormat.setLenient(true);
Date d = inputDateFormat.parse(dateValue);
expectedFormat = outputDateFormat.format(d);
} catch (Exception e) {
// Sending back the current datetime in the desired format
Calendar cal = Calendar.getInstance();
expectedFormat = outputDateFormat.format(cal.getTime());
}
return expectedFormat;
}
}
Under Java 7 and higher, you can use XXX to output the time zone with a column:
SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
When you use this to format a data, it will return for example:
2001-07-04T12:08:56-07:00
See the documentation for more examples.
Since I'm using 1.6, XXX is not supported. So used alternative way to achieve this. This is what I did for alternative way..
public static String formattedDate (String dateValue) {
StringBuilder expectedFormat;
SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
try {
if (dateValue == null || dateValue.isEmpty()) {
dateValue = "";
}
inputDateFormat.setLenient(false);
Date d = inputDateFormat.parse(dateValue);
} catch (Exception e) {
System.out.println("Error in parsing : " + e.getMessage());
// Sending back the current datetime in the desired format
Calendar cal = Calendar.getInstance();
dateValue = inputDateFormat.format(cal.getTime());
} finally {
expectedFormat = new StringBuilder(dateValue).insert(dateValue.length()-2, ":");
}
return expectedFormat.toString();
}
When you need only the third last character changed and give a string as a parameter how about leaving it a String?
public static String formattedDate (String dateValue)
{
return dateValue.substring(0, dateValue.length() - 2)
+ ":"
+ dateValue.substring(dateValue.length() - 2);
}
Output:
a => 2015-10-19T16:52:23-04:00
I have a String Array which is contain dates that read from a CSV file.
Now I want to count how many weekend days are in that array. But in my array there are some dates are duplicated. Here shows part of the data that is containing in my Array.
12/2/2010
12/3/2010
12/5/2010
12/10/2010
12/5/2010
12/13/2010
12/14/2010
12/12/2010
In this data set 12/5/2010 is Sunday (but there are two records) & 12/12/2010 is Saturday (has One record). In output, I want to print number of weekend days in this array using java. Compared to this example the Answer should be 2.
FileInputStream fis=new FileInputStream("c:/cdr2.csv");
InputStreamReader isr=new InputStreamReader(fis);
BufferedReader bf = new BufferedReader(isr);
while (bf.ready()) {
String line = bf.readLine();
String[] values=line.split(",");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/d/yyyy");
Date date = simpleDateFormat.parse(values[2]);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
}
First, you need to write a method that determines if a given Date is a weekend or not:
public static boolean isWeekend(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
return dayOfWeek == Calendar.SUNDAY || dayOfWeek == Calendar.SATURDAY;
}
Then, you need to define a DateFormat, so that you can parse a date String into a java.util.Date. Finally, you can use a Set to assure every weekend you find is not going to be duplicated:
public static void main(String[] args) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String[] dates = { "12/2/2010", "12/3/2010", "12/5/2010", "12/10/2010", "12/5/2010", "12/13/2010", "12/14/2010", "12/12/2010" };
Set<String> weekends = new HashSet<String>();
for (String dt : dates) {
Date date = dateFormat.parse(dt);
if (isWeekend(date)) {
weekends.add(dt);
}
}
System.out.println("There are " + weekends.size() + " distinct weekends."); // 2
}
I would say you need to first remove duplicates and then check which of them are weekend days:
Set<String> set = new HashSet<String>( Arrays.asList(yourArrayOfDateStrings) );
DateFormat df = new SimpleDateFormat(yourDatePattern);
Calendar calendar = Calendar.getInstance();
int weekendDays = 0;
for (String dateString : set) {
calendar.setTime( df.parse(dateString) );
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) {
weekendDays++;
}
}
I don't use java date, ever!
I agree with Costi Ciudatu, use a Set to remove duplicates.
:) please to send you teh codez using JodaTime
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.DateTimeField;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
public class Dates
{
static String[] localTestDate = new String[] {"12/2/2010", "12/3/2010", "12/5/2010", "12/10/2010", "12/5/2010", "12/13/2010", "12/14/2010", "12/12/2010"};
static DateTimeFormatter dateFactory = DateTimeFormat.forPattern("MM/d/yyyy");
public static void main(String[] args)
{
// final Set<DateTime> uniqueDates = generateUniqueDates(localTestDate);
final Set<DateTime> uniqueDates = generateUniqueDates(readCommonSeparatedFile(args[0]));
int numberOfWeekendDates = 0;
for(DateTime date : uniqueDates)
{
if(isWeekend(date)) numberOfWeekendDates++;
}
System.out.println("There are " + numberOfWeekendDates + " weekend days in your list.");
}
private static boolean isWeekend(DateTime dateTime)
{
return (DateTimeConstants.SATURDAY == dateTime.dayOfWeek().get() || DateTimeConstants.SUNDAY == dateTime.dayOfWeek().get());
}
private static String[] readCommonSeparatedFile(final String fileName)
{
FileInputStream fileInputStream = null;
String[] result = null;
try
{
fileInputStream = new FileInputStream(fileName);
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
while (bufferedReader.ready())
{
String line = bufferedReader.readLine();
result = line.split(",");
}
}
catch (IOException e)
{
//log error some where
throw new RuntimeException("aw, snap!");
}
return result;
}
private static Set<DateTime> generateUniqueDates(final String[] dates)
{
final Set<DateTime> dateTimes = new HashSet<DateTime>();
for (String date : dates)
{
dateTimes.add(dateFactory.parseDateTime(date).toDateTime());
}
return dateTimes;
}
}