I cannot set the AM_PM variable in Java 8 Micro Edition - calendar

I'm a teaching myself Java and am a beginner. As part of a larger project I am running code to determine, and then later set, the time on a Calendar object. I have scoured the internet for a way to set the AM_PM value but I cannot get it to work. Any suggestions would help.
package timethread;
import javax.microedition.midlet.MIDlet;
import java.util.Calendar;
/**
*
* #author Jaydawg
*/
public class TimeThread extends MIDlet {
#Override
public void startApp() {
Calendar cal = Calendar.getInstance();
System.out.println(cal.get(Calendar.AM_PM)); // Original value: it is '1' or PM
cal.add(Calendar.AM_PM, 0); // Attempt #1
System.out.println(cal.get(Calendar.AM_PM));
cal.set(Calendar.AM_PM, 0); // Attempt #2
System.out.println(cal.get(Calendar.AM_PM));
cal.set(Calendar.AM_PM, Calendar.AM); //Attempt #3
System.out.println(cal.get(Calendar.AM_PM));
cal.add(Calendar.AM_PM, Calendar.AM); //Attempt #4
System.out.println(cal.get(Calendar.AM_PM));
int min = cal.get(Calendar.MINUTE);
int sec = cal.get(Calendar.SECOND);
int hour = cal.get(Calendar.HOUR);
int AMPM = cal.get(Calendar.AM_PM);
System.out.println(AMPM);
String AMPMString = "AM";
if(cal.get(Calendar.AM_PM)==1){
AMPMString = "PM";
}
System.out.println("The time is " + hour + ":" + min + ":" + sec + " " + AMPMString);
}
My results were as follows:
1
1
1
1
1
1
The time is 1:20:42 PM

Maybe a bug with Calendar in Java 8 Micro Edition?
This works for me with Java 7:
Calendar c = Calendar.getInstance();
c.set(Calendar.AM_PM, Calendar.AM);
System.out.println(c.get(Calendar.AM_PM));
c.set(Calendar.AM_PM, Calendar.PM);
System.out.println(c.get(Calendar.AM_PM));
it outputs:
0
1

This was confirmed to be a bug by Oracle.
https://community.oracle.com/thread/3728182?sr=inbox&ru=997534

Related

How to create a datepicker in react js

I tried different method to develop date picker in reactJS. I done with "react-datepicker" package and it return "Wed May 15 2019 12:54:33 GMT+0100" as a result but I need 12/12/2000 format
try to format it as you want
const pickerDate = new Date('Wed May 15 2019 12:54:33 GMT+0100')
const day = pickerDate.getDay() < 10 ? '0' + pickerDate.getDay() : pickerDate.getDay()
const month = pickerDate.getMonth() + 1 < 10 ? '0' + (pickerDate.getMonth() + 1) : pickerDate.getMonth() + 1
const year = pickerDate.getFullYear()
const formatedDate = `${day}/${month}/${year}`
you can also use third part libraries like moment

do we need to write a batchable class to schedule a class

I am trying to generate a report and send a report to email as an attachment in salesforce. I have created a controller, created a class for csv stream and an email template. I want to schedule the class. when I schedule it I am unable to achieve the result. Could anyone help me in achieving this?
The code I tried is created a visualforce component, class, and an email template.
The code I tried is to schedule it for every 5 minutes. but I am getting an error.
Do we need to write a batchable class for this
global class IncrementReport implements Schedulable {
global void execute(SchedulableContext ctx) {
System.debug('Entered Cron trigger');
rptobj__c r = [SELECT Id, Name, reporttrigger__c FROM rptobj__c WHERE Name = 'ThisReport' LIMIT 1];
r.reporttrigger__c += 1;
String s = '0 0 * * * ?' ';
IncrementReport abc = new IncrementReport();
system.schedule('Report Job', s, abc);
System.debug('updating trigger to: ' + r.reporttrigger__c);
update r;
}
}
You only write the logic in your scheduler class.
global class IncrementReport implements Schedulable {
global void execute(SchedulableContext ctx) {
System.debug('Entered Cron trigger');
rptobj__c r = [SELECT Id, Name, reporttrigger__c FROM rptobj__c WHERE Name = 'ThisReport' LIMIT 1];
r.reporttrigger__c += 1;
System.debug('updating trigger to: ' + r.reporttrigger__c);
update r;
}
}
And then, can run this cron expression from Developer Console.
String sch1 = '0 0 * * * ?';
IncrementReport ir1 = new IncrementReport();
system.schedule('Every Hour plus 0 min', sch1, ir1);
String sch2 = '0 5 * * * ?';
IncrementReport ir2 = new IncrementReport();
system.schedule('Every Hour plus 5 min', sch2, ir2);
String sch3 = '0 10 * * * ?';
IncrementReport ir3 = new IncrementReport();
system.schedule('Every Hour plus 10 min', sch3, ir3);
String sch4 = '0 15 * * * ?';
IncrementReport ir4 = new IncrementReport();
system.schedule('Every Hour plus 15 min', sch4, ir4);
// And so on ir5, ir6 .... ir12
As you want to run the scheduler in every 5 minutes, you have to system.schedule 12 times as 12*5 = 60 minutes = 1 hour
You can see whether the job is running or not on
Setup -> Scheduled Jobs

get the difference between 2 date & time by hours, minutes and seconds using cakephp

I'm trying to get the difference between a datetime and a current datetime using cakephp . I succeeded to get it but I want to convert it to only hours ,minutes and seconds .
here is my code :
$currDateTime = Time::now();
$date1 = $plan->start_day->format('Y-m-d');
$date2 = $currDateTime->format('Y-m-d');
$diff = abs(strtotime($date1) - strtotime($date2));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24)) ;
$time1 = $plan->start_day->format('H:i:s');
$time2 = $currDateTime->format('H:i:s');
$seconds = abs(strtotime($time1) - strtotime($time2));
$hours = floor($seconds / 3600);
$mins = floor(($seconds - ($hours*3600)) / 60);
$secs = floor($seconds % 60);
the result is a difference in years, months, days, hours, minutes and seconds.
how can I convert it to only H:m:s ??
There's no need for all these calculations, simply create a DateInterval diff using the diff() method provided by the time object, and use the days, h, i, and s values it provides to create your desired output. The only calculation that would be required, would be to add the days in hours.
$diff = $currDateTime->diff($plan->start_day);
$formatted = sprintf('%02d:%02d:%02d', ($diff->days * 24) + $diff->h, $diff->i, $diff->s);
See also
PHP Manual > Date/Time > DateTimeInterface > DateTimeInterface::diff
PHP Manual > Date/Time > DateInterval

Solr 6.0.0 - SolrCloud java example

I have solr installed on my localhost.
I started standard solr cloud example with embedded zookeepr.
collection: gettingstarted
shards: 2
replication : 2
500 records/docs to process time took 115 seconds[localhost tetsing] -
why is this taking this much time to process just 500 records.
is there a way to improve this to some millisecs/nanosecs
NOTE:
I have tested the same on remote machine solr instance, localhost having data index on remote solr [inside java commented]
I started my solr myCloudData collection with Ensemble with single zookeepr.
2 solr nodes,
1 Ensemble zookeeper standalone
collection: myCloudData,
shards: 2,
replication : 2
Solr colud java code
package com.test.solr.basic;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.common.SolrInputDocument;
public class SolrjPopulatorCloudClient2 {
public static void main(String[] args) throws IOException,SolrServerException {
//String zkHosts = "64.101.49.57:2181/solr";
String zkHosts = "localhost:9983";
CloudSolrClient solrCloudClient = new CloudSolrClient(zkHosts, true);
//solrCloudClient.setDefaultCollection("myCloudData");
solrCloudClient.setDefaultCollection("gettingstarted");
/*
// Thread Safe
solrClient = new ConcurrentUpdateSolrClient(urlString, queueSize, threadCount);
*/
// Depreciated - client
//HttpSolrServer server = new HttpSolrServer("http://localhost:8983/solr");
long start = System.nanoTime();
for (int i = 0; i < 500; ++i) {
SolrInputDocument doc = new SolrInputDocument();
doc.addField("cat", "book");
doc.addField("id", "book-" + i);
doc.addField("name", "The Legend of the Hobbit part " + i);
solrCloudClient.add(doc);
if (i % 100 == 0)
System.out.println(" Every 100 records flush it");
solrCloudClient.commit(); // periodically flush
}
solrCloudClient.commit();
solrCloudClient.close();
long end = System.nanoTime();
long seconds = TimeUnit.NANOSECONDS.toSeconds(end - start);
System.out.println(" All records are indexed, took " + seconds + " seconds");
}
}
You are committing every new document, which is not necessary. It will run a lot faster if you change the if (i % 100 == 0) block to read
if (i % 100 == 0) {
System.out.println(" Every 100 records flush it");
solrCloudClient.commit(); // periodically flush
}
On my machine, this indexes your 500 records in 14 seconds. If I remove the commit() call from the for loop, it indexes in 7 seconds.
Alternatively, you can add a commitWithinMs parameter to the solrCloudClient.add() call:
solrCloudClient.add(doc, 15000);
This will guarantee your records are committed within 15 seconds, and also increase your indexing speed.

"Week of the year" Algorithm needs improvements

I have an algorithm which scans through data read from a .csv file(approx 3700 lines) and assess's which trading week of the year each entry is in by running a count++ for every Sunday of that year and assigning the count value as the trading week when the date falls within that week.
It's working but performance is lagging. It is the 3rd function running using Task.Factory.StartNew (I have also tried parallel.Invoke).
Results of timing tests.
before: 00:00:05.58
after: 00:00:23.27
UPDATE
Added break after each trading week is set. Time improved but still slow.
new time: 00:00:15.74
For our purposes the 1st week of the year is week 1(not 0) and is defined as from the first day of the year until the Sunday. If the first day of the year is a Sunday the length of week 1 is 1 day.
private void SetDefiniteWeeks()
{
string FileLoc = FilePath + Market + ".csv";
string[] Data = File.ReadAllLines(FileLoc);
var FileData = from D in Data
let DataSplit = D.Split(',')
select new
{
Date = DateTime.Parse(DataSplit[0]),
ClosingPrice = double.Parse(DataSplit[4])
};
//assign each date to it's relevant week
TradingWeek TW;
List<TradingWeek> tradingWeek = new List<TradingWeek>();
foreach (var pe in FileData)
{
// DateTime dt = pe.Date;
int Year = pe.Date.Year;
string End_of_Week = "Sunday";
int WeekCount = 0;
DateTime LoopDate_Begin = new DateTime(Year,1,1);
DateTime LoopDate_End = new DateTime(Year,12,31);
do
{
if (LoopDate_Begin.DayOfWeek.ToString() == End_of_Week)
{
WeekCount++;
if (LoopDate_Begin.DayOfYear > pe.Date.DayOfYear && LoopDate_Begin.DayOfYear < (pe.Date.DayOfYear + 7))
{
TW = new TradingWeek { Week = WeekCount, Date = pe.Date };
tradingWeek.Add(TW);
break;
}
}
LoopDate_Begin = LoopDate_Begin.AddDays(1);
} while (LoopDate_Begin.Date.ToString() != LoopDate_End.Date.ToString());
}
}
Please help.
UPDATE
NEW TIME
00:00:06.686
A vast improvement. Thanks all for your help.
Revised code:
CalendarWeekRule cw = CalendarWeekRule.FirstDay;
var calendar = CultureInfo.CurrentCulture.Calendar;
var trad_Week = (from pe in FileData
select new TradingWeek
{
Date = pe.Date,
Week = (calendar.GetWeekOfYear(pe.Date, cw,DayOfWeek.Sunday))
}).ToList();
Im not sure if this is what you want but after reading the comments I got the feeling that this might work (?)
var calendar = CultureInfo.CurrentCulture.Calendar;
var tradingWeek = (from pe in FileData
select new TradingWeek
{
Date = pe.Date,
Week = calendar.GetWeekOfYear(pe.Date, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
}).ToList();
Edit: Changed to CalendarWeekRule.FirstDay since it's (more?) what OP is looking for.
Three quick thoughts:
Why are you only adding one day each time and checking to see if it's Sunday. Surely once you have found your first Sunday you can add seven days to find the next one?
If you order your pes by DateTime before you start then you don't need to restart at the beginning of the year for each one, you can pick up where you left off.
As Nicolas says, break after adding the trading week. No need to go through the rest of the year after you already know what the answer is.
I guess you'll end up with something like this (may or may not actually work, but should be close enough)
TradingWeek TW;
List<TradingWeek> tradingWeek = new List<TradingWeek>();
string End_of_Week = "Sunday";
var orderedData = FileData.OrderBy(x => x.Date)
DateTime LoopDate_Begin = new DateTime(orderedData[0].Date.Year,1,1);
int WeekCount = 1;
while (LoopDate_Begin.DayOfWeek.ToString() != End_of_Week)
{
LoopDate_Begin = LoopDate_Begin.AddDays(1);
}
foreach (var pe in orderedData)
{
do
{
if (LoopDate_Begin.DayOfYear > pe.Date.DayOfYear && LoopDate_Begin.DayOfYear < (pe.Date.DayOfYear + 7))
{
TW = new TradingWeek { Week = WeekCount, Date = pe.Date };
tradingWeek.Add(TW);
break;
}
WeekCount++;
LoopDate_Begin = LoopDate_Begin.AddDays(7);
} while (true); //need to be careful here
}
if I get you correctly, you don't need to look any further as soon as you've added your TradingWeek
So, you can
break;
after
tradingWeek.Add(TW);
You could then even leave out the
&& LoopDate_Begin.DayOfYear < (pe.Date.DayOfYear + 7)
condition since the first part is going to be true only once: for your desired interval.
You might even go for a loopless approach by dividing the number of days since your starting week by 7 - and doing some cleaning up work ;)
Can you get rid of your do loop altogether by calculating the Week Number directly? Something like the accepted answer here.
Following #nicolas78's response, something like this should work
int Year = pe.Date.Year;
DateTime Year_Begin = new DateTime(Year,1,1);
int Jan1DayOfWeek = Year_Begin.DayOfWeek;
foreach (var pe in FileData)
{
int WeekCount = (pe.Date.DayOfYear - Jan1DayOfWeek) % 7 + 1;
TradingWeek TW = new TradingWeek { Week = WeekCount, Date = pe.Date };
tradingWeek.Add(TW);
}
Depending on how DayOfWeek and DayOfYear count, that is from 0 or 1, and how your mod operation work, you may need to tweak the WeekCount computation a bit.
There's a built-in feature to get the week of the year based on the date in .NET. An example is shown below, but it may need some tweaking to fit your business scenario:
System.Globalization.CultureInfo myCI = new System.Globalization.CultureInfo("en-US");
int week = myCI.Calendar.GetWeekOfYear(DateTime.Now.ToUniversalTime(), System.Globalization.CalendarWeekRule.FirstFourDayWeek, System.DayOfWeek.Sunday);
You don't need to count at all - just do a quick calculation. This assumes that a partial week at the start of the year is week 1 and week 2 begins on the first Monday.
List<TradingWeek> tradingWeek = new List<TradingWeek>();
foreach (var pe in FileData)
{
var date = pe.Date;
while (date.DayOfWeek != DayOfWeek.Sunday)
date = date.AddDays(1);
var week = date.DayOfYear/7+1;
var TW = new TradingWeek {Week = week, Date = pe.Date};
tradingWeek.Add(TW);
}

Resources