Share

Search Java Code Snippets


  Help us in improving the repository. Add new snippets through 'Submit Code Snippet ' link.





#Java - Code Snippets for '#Date' - 31 code snippet(s) found

 Sample 1. Get Date using ZonedDateTime and LocalDateTime

ZonedDateTime zonedDatetime = ZonedDateTime.of(201, 1, 31, 14, 35, 12, 123, ZoneId.of("UTC-11"));
System.out.println(zonedDatetime.get(ChronoField.HOUR_OF_DAY));

LocalDateTime localDateTime = LocalDateTime.of(2015, 03, 10, 13, 36);
System.out.println(localDateTime);

ZonedDateTime zonedDatetime2 = ZonedDateTime.now(ZoneId.of("merica/Chicago"));
System.out.println(zonedDatetime2);

ZonedDateTime zonedDatetime3 = ZonedDateTime.of(localDateTime, ZoneId.of("America/Chicago"));
System.out.println(zonedDatetime3);

   Like      Feedback     ZonedDateTime   LocalDateTime   ZonedDateTime.of  LocalDateTime.of  ZonedDateTime.now  ZoneId  ZoneId.of  java.time.ZonedDateTime  java.time   java 8


 Sample 2. Initialize Date using SimpleDateFormat and parsing string

Date endDate = new SimpleDateFormat("yyyyMMdd").parse("20160426");

   Like      Feedback     SimpleDateFormat   Date   SimpleDateFormat.parse  java.text.SimpleDateFormat


 Sample 3. Initialize Joda DateTime

DateTime dt = new DateTime("2016-12-18T22:34:41.311-07:00");

   Like      Feedback     DateTime   Joda


 Sample 4. Initialize java.util.date using java.util.Calendar

Date currentDate = Calendar.getInstance().getTime();

   Like      Feedback     calendar  java.util.calendar  java.util  date  java.util.date  Calendar.getTime


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 5. Method to get Date after n days using Calendar

Date getDateAfterDays(int numberOfDays){
   Calendar futureDate = Calendar.getInstance();
   futureDate.setTime(new Date()); // Set Current Date
   futureDate.add(Calendar.DATE, numberOfDays); // Add n days to current Date

   return new Date(futureDate.getTimeInMillis());
}

   Like      Feedback     date   calendar   java.util  calendar.add  calendar.date  calendar.settime  calendar.gettimeinmillis


 Sample 6. Get Date and Time after few Hours

Date getDateTimeAfterNHours(int numberOfHours){
   Calendar futureTime = Calendar.getInstance();
   futureTime.setTime(new Date()); // Set Current Date
   futureTime.add(Calendar.HOUR, numberOfDays); // Add n hours to current Date and Time

   return new Date(futureTime.getTimeInMillis());
}

   Like      Feedback     date   calendar   java.util  calendar.add  calendar.hour  calendar.settime  calendar.gettimeinmillis


 Sample 7. Today's Date as per Hijrah Chronology

AbstractChronology abstractChrono = HijrahChronology.INSTANCE;
System.out.println(abstractChrono.dateNow());

   Like      Feedback     Hijrah Date  Hijrah Calendar  Hijrah Chronology  HijrahChronology  java 8  HijrahChronology.INSTANCE  AbstractChronology  AbstractChronology.datenow


 Sample 8. Today's Date as per Japanese Chronology

AbstractChronology abstractChrono = JapaneseChronology.INSTANCE;
System.out.println(abstractChrono.dateNow());

   Like      Feedback     Japanese Chronology  JapaneseChronology  java 8  JapaneseChronology.INSTANCE  AbstractChronology  AbstractChronology.datenow


 Sample 9. Todays Date as per Minguo Chronology

AbstractChronology abstractChrono = MinguoChronology.INSTANCE;
System.out.println(abstractChrono.dateNow());

   Like      Feedback     Minguo Chronology  MinguoChronology  java 8  MinguoChronology.INSTANCE  AbstractChronology  AbstractChronology.datenow


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 10. Todays Date as per ThaiBuddhistChronology

AbstractChronology abstractChrono = ThaiBuddhistChronology.INSTANCE;

System.out.println(abstractChrono.dateNow());

   Like      Feedback     ThaiBuddhist Chronology  ThaiBuddhistChronology  java 8  ThaiBuddhistChronology.INSTANCE  AbstractChronology  AbstractChronology.datenow


 Sample 11. Time Taken to call a method or service

Date date1 = new Date();

// Call Service or Method

Date date2 = new Date();
System.out.println(TimeUnit.SECONDS.convert(date2.getTime()-date1.getTime(), TimeUnit.MILLISECONDS));// Time Taken in Seconds
System.out.println(TimeUnit.MINUTES.convert(date2.getTime()-date1.getTime(), TimeUnit.MILLISECONDS));// Time Taken in Minutes
System.out.println(TimeUnit.HOURS.convert(date2.getTime()-date1.getTime(), TimeUnit.MILLISECONDS));// Time Taken in Hours

   Like      Feedback     Difference between 2 dates  Time to call a method  TimeUnit  Date.java.util.Date


 Sample 12. Usage of org.joda.time.DateMidnight

DateMidnight currentDate = new DateMidnight();
DateMidnight dateafterAMonth = currentDate.plusMonths(1);
Date javaSedateAfterAMonth = dateafterAMonth.toDate();

   Like      Feedback     org.joda.time.DateMidnight  java.util.Date  Date  Add month to Date


 Sample 13. Use java.time.format.DateTimeFormatter to Parse date in the format YYYYMMDD+HHmmss

DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendValue(YEAR, 4)
.appendValue(MONTH_OF_YEAR, 2)
.appendValue(DAY_OF_MONTH, 2)
.appendOffset("+HHMMss", "Z")
.toFormatter();

TemporalAccessor temporal = null;

try {
temporal = dateTimeFormatter.parse("2016101+235700");
System.out.println(temporal.toString()); // prints {OffsetSeconds=86220},ISO resolved to 2016-01-01
} catch (DateTimeParseException ex){
System.out.println("Error parsing date");
}

   Like      Feedback     DateTimeFormatter   Parse Date in Java 8   Parse date using DateTimeFormatter and DateTimeFormatterBuilder


 Sample 14. Get Yesterdays Date using Apache Commons DateUtils

Date yesterdayDate = DateUtils.addDays(new Date(), -1);

   Like      Feedback     DateUtils  Apache Commons


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 15. Assign value to BigInteger upon validating the value using BigIntegerValidator ( Apache Commons )

BigIntegerValidator bigIntegerValidator = BigIntegerValidator.getInstance();
BigInteger bigInteger = bigIntegerValidator.validate("1AD2345");
System.out.println(bigInteger); // prints null as the validation fails because of non numeric characters

   Like      Feedback     Validate a Number  Apache Commons  Assign if the Number is valid  BigInteger


 Sample 16. Validate an IP Address using InetAddressValidator ( Apache Commons )

InetAddressValidator inetAddressValidator =
InetAddressValidator.getInstance();
if (inetAddressValidator.isValid("123.123.123.123")) {
System.out.println("true"); // prints true
}

if (inetAddressValidator.isValid("www.buggybread.com")) {
System.out.println("true"); // doesn't print true here
}

   Like      Feedback     Validate IP Address   Apache Commons Validator


 Sample 17. Get the Date object using the TimeZone

TimeZone zone = (TimeZone.getDefault().getRawOffset() == EET.getRawOffset() ? EST : EET);
Date expectedZone = createCalendar(zone, 20051231, 0).getTime();

   Like      Feedback     TimeZone  java.util.TimeZone  Date  Calendar


 Sample 18. Code Sample / Example / Snippet of java.text.SimpleDateFormat

    private static String getNameOrAbbrev(String format)

{

Calendar cal = Calendar.getInstance();

SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.ENGLISH);

return dateFormat.format(cal.getTime());

}


   Like      Feedback      java.text.SimpleDateFormat


 Sample 19. Code Sample / Example / Snippet of java.time.LocalDateTime

    public boolean equals(Object obj) {

if (this == obj) {

return true;

}

if (obj instanceof LocalDateTime) {

LocalDateTime other = (LocalDateTime) obj;

return date.equals(other.date) && time.equals(other.time);

}

return false;

}


   Like      Feedback      java.time.LocalDateTime


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 20. Code Sample / Example / Snippet of java.time.ZonedDateTime

    public long until(Temporal endExclusive, TemporalUnit unit) {

ZonedDateTime end = ZonedDateTime.from(endExclusive);

if (unit instanceof ChronoUnit) {

end = end.withZoneSameInstant(zone);

if (unit.isDateBased()) {

return dateTime.until(end.dateTime, unit);

} else {

return toOffsetDateTime().until(end.toOffsetDateTime(), unit);

}

}

return unit.between(this, end);

}


   Like      Feedback      java.time.ZonedDateTime


 Sample 21. Code Sample / Example / Snippet of java.time.LocalDate

    public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute) {

LocalDate date = LocalDate.of(year, month, dayOfMonth);

LocalTime time = LocalTime.of(hour, minute);

return new LocalDateTime(date, time);

}


   Like      Feedback      java.time.LocalDate


 Sample 22. Code Sample / Example / Snippet of org.apache.calcite.sql.validate.SqlMonotonicity

  public void checkMonotonic(String query,

SqlMonotonicity expectedMonotonicity) {

SqlValidator validator = getValidator();

SqlNode n = parseAndValidate(validator, query);

final RelDataType rowType = validator.getValidatedNodeType(n);

final SqlValidatorNamespace selectNamespace = validator.getNamespace(n);

final String field0 = rowType.getFieldList().get(0).getName();

final SqlMonotonicity monotonicity =

selectNamespace.getMonotonicity(field0);

assertThat(monotonicity, equalTo(expectedMonotonicity));

}


   Like      Feedback      org.apache.calcite.sql.validate.SqlMonotonicity


 Sample 23. Code Sample / Example / Snippet of org.apache.calcite.sql.validate.SqlValidatorNamespace

  public void checkMonotonic(String query,

SqlMonotonicity expectedMonotonicity) {

SqlValidator validator = getValidator();

SqlNode n = parseAndValidate(validator, query);

final RelDataType rowType = validator.getValidatedNodeType(n);

final SqlValidatorNamespace selectNamespace = validator.getNamespace(n);

final String field0 = rowType.getFieldList().get(0).getName();

final SqlMonotonicity monotonicity =

selectNamespace.getMonotonicity(field0);

assertThat(monotonicity, equalTo(expectedMonotonicity));

}


   Like      Feedback      org.apache.calcite.sql.validate.SqlValidatorNamespace


 Sample 24. Code Sample / Example / Snippet of org.apache.calcite.sql.validate.SqlValidator

  public void checkFieldOrigin(String sql, String fieldOriginList) {

SqlValidator validator = getValidator();

SqlNode n = parseAndValidate(validator, sql);

final List<List<String>> list = validator.getFieldOrigins(n);

final StringBuilder buf = new StringBuilder("{");

int i = 0;

for (List<String> strings : list) {

if (i++ > 0) {

buf.append(", ");

}

if (strings == null) {

buf.append("null");

} else {

int j = 0;

for (String s : strings) {

if (j++ > 0) {

buf.append('.');

}

buf.append(s);

}

}

}

buf.append("}");

assertEquals(fieldOriginList, buf.toString());

}


   Like      Feedback      org.apache.calcite.sql.validate.SqlValidator


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 25. Code Sample / Example / Snippet of org.apache.calcite.sql.validate.SqlValidatorScope

  public SqlMonotonicity getMonotonicity(String sql) {

final SqlValidator validator = getValidator();

final SqlNode node = parseAndValidate(validator, sql);

final SqlSelect select = (SqlSelect) node;

final SqlNode selectItem0 = select.getSelectList().get(0);

final SqlValidatorScope scope = validator.getSelectScope(select);

return selectItem0.getMonotonicity(scope);

}


   Like      Feedback      org.apache.calcite.sql.validate.SqlValidatorScope


 Sample 26. Code Sample / Example / Snippet of org.apache.calcite.sql.validate.SqlConformance

    public AdvisorTesterFactory() {

super(DefaultSqlTestFactory.INSTANCE);

}



@Override public SqlValidator getValidator(SqlTestFactory factory) {

final RelDataTypeFactory typeFactory =

new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);

final SqlConformance conformance = (SqlConformance) get("conformance");

final boolean caseSensitive = (Boolean) factory.get("caseSensitive");

return new SqlAdvisorValidator(

SqlStdOperatorTable.instance(),

new MockCatalogReader(typeFactory, caseSensitive).init(),

typeFactory,

conformance);

}


   Like      Feedback      org.apache.calcite.sql.validate.SqlConformance


 Sample 27. Code Sample / Example / Snippet of org.apache.calcite.sql.validate.SqlValidatorTable

    public RelOptTable getTableForMember(List<String> names) {

final SqlValidatorTable table = catalogReader.getTable(names);

final RelDataType rowType = table.getRowType();

final List<RelCollation> collationList = deduceMonotonicity(table);

if (names.size() < 3) {

String[] newNames2 = {"CATALOG", "SALES", ""};

List<String> newNames = new ArrayList<>();

int i = 0;

while (newNames.size() < newNames2.length) {

newNames.add(i, newNames2[i]);

++i;

}

names = newNames;

}

return createColumnSet(table, names, rowType, collationList);

}


   Like      Feedback      org.apache.calcite.sql.validate.SqlValidatorTable


 Sample 28. Code Sample / Example / Snippet of org.apache.hc.core5.http.protocol.RequestValidateHost

    public void testRequestHttp11HostHeaderPresent() throws Exception {

final HttpContext context = new BasicHttpContext(null);

final BasicHttpRequest request = new BasicHttpRequest("GET", "/", HttpVersion.HTTP_1_1);

request.setHeader(HttpHeaders.HOST, "blah");

final RequestValidateHost interceptor = new RequestValidateHost();

interceptor.process(request, context);

}


   Like      Feedback      org.apache.hc.core5.http.protocol.RequestValidateHost


 Sample 29. Populate DateFormat using SimpleDateFormat

public JsonElement serialize(Event e, Type typeOfSrc, JsonSerializationContext context) {
DateFormat format = SimpleDateFormat.getDateTimeInstance();
JsonObject event = new JsonObject();
event.addProperty("time", format.format(new Date(e.getTime())));
return event;
}

   Like      Feedback      java.text.DateFormat  SimpleDateFormat.getDateTimeInstance()  SimpleDateFormat


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 30. Update Google Adwords Bids for a particular keyword using Keyword Id

Usage of

import com.google.api.ads.adwords.axis.v201802.cm.AdGroupCriterion;
import com.google.api.ads.adwords.axis.v201802.cm.AdGroupCriterionOperation;
import com.google.api.ads.adwords.axis.v201802.cm.AdGroupCriterionReturnValue;
import com.google.api.ads.adwords.axis.v201802.cm.AdGroupCriterionServiceInterface;
import com.google.api.ads.adwords.axis.v201802.cm.BiddableAdGroupCriterion;
import com.google.api.ads.adwords.axis.v201802.cm.BiddingStrategyConfiguration;
import com.google.api.ads.adwords.axis.v201802.cm.Bids;
import com.google.api.ads.adwords.axis.v201802.cm.CampaignCriterionServiceInterface;
import com.google.api.ads.adwords.axis.v201802.cm.CpcBid;
import com.google.api.ads.adwords.axis.v201802.cm.Keyword;
import com.google.api.ads.adwords.axis.v201802.cm.Money;

public void updateBidForKeyword(Long adGroupId, Long keywordId, Long bidAmount) {
      
AdWordsSession adwordSession = null;

// initialize AdWords session

try {
            // Generate a refreshable OAuth2 credential
            Credential oAuth2Credential = new OfflineCredentials.Builder().forApi(Api.ADWORDS)
                  .fromFile().build()
                  .generateCredential();

            // Construct an AdWordsSession.
            adwordSession = new AdWordsSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build();

         } catch (Exception ex) {

         }

// Get CampaignCriterionService using AdWordsSession

AdWordsServices adWordsServices = new AdWordsServices();

      CampaignCriterionServiceInterface campaignCriterionService = adWordsServices.get(adwordSession, CampaignCriterionServiceInterface.class);

      AdGroupCriterionServiceInterface adGroupCriterionService = GoogleAuthenticationService
            .getAdGroupCriterionService();

      Keyword keyword = new Keyword();
      keyword.setId(keywordId);

      BiddableAdGroupCriterion keywordBiddableAdGroupCriterion = new BiddableAdGroupCriterion();
      keywordBiddableAdGroupCriterion.setAdGroupId(adGroupId);
      keywordBiddableAdGroupCriterion.setCriterion(keyword);

      BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration();
      CpcBid bid = new CpcBid();
      bid.setBid(new Money(null, bidAmount));
      biddingStrategyConfiguration.setBids(new Bids[] { bid });
      keywordBiddableAdGroupCriterion.setBiddingStrategyConfiguration(biddingStrategyConfiguration);

      AdGroupCriterionOperation keywordAdGroupCriterionOperation = new AdGroupCriterionOperation();
      keywordAdGroupCriterionOperation.setOperand(keywordBiddableAdGroupCriterion);
      keywordAdGroupCriterionOperation.setOperator(Operator.SET);

      AdGroupCriterionOperation[] operations = new AdGroupCriterionOperation[] { keywordAdGroupCriterionOperation };

      AdGroupCriterionReturnValue result = null;

      try {
         result = adGroupCriterionService.mutate(operations);
      } catch (Exception e) {
         e.printStackTrace();
      }
      
      // Display campaigns.
      for (AdGroupCriterion campaignCriterion : result.getValue()) {
         System.out.printf("Campaign criterion with criterion ID %d, " + "and type '%s' was added.%n",
               campaignCriterion.getCriterion().getId(), campaignCriterion.getCriterion().getCriterionType());
      }

   }

   Like      Feedback     Google Adwords  Adwords  Adwords Java Api  Update Adwords Bids  Update Adwords Bids for keyword


 Sample 31. Custom Date Range for Google Adwords Report

// Create a Report Definition

ReportDefinition reportDefinition = new ReportDefinition();

// Set the Repo Date Range type as Custom Date

reportDefinition.setDateRangeType(ReportDefinitionDateRangeType.CUSTOM_DATE);

// Create. a date format as Google want date as string a specific format

SimpleDateFormat dateFormat = new SimpleDateFormat("YYYYMMDD", Locale.getDefault());
      
// Create selector

Selector selector = new Selector();

// Add fields to selector

selector.getFields()
            .addAll(Arrays.asList("Id", "CampaignName");

// Set Min and Max date to the selector
      
selector.getDateRange().setMin(dateFormat.format(startDate));
selector.getDateRange().setMax(dateFormat.format(endDate));

// Add selector to Report Definition

reportDefinition.setSelector(selector);

   Like      Feedback     Adwords Reports  Google Adwords  Adwords  Custom Date Range for Google Adwords report  Custom Date Range for Adwords  ReportDefinitionDateRangeType.CUSTOM_DATE



Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner



comments powered by Disqus