如何实现点击时更新字符串格式当前日期时间?Firebase子元素填充问题
Let's break down how to handle both of your technical requirements step by step:
1. Update Formatted Date/Time String on Click
First, we'll create a reusable way to generate the formatted date/time string, then update your target string (or UI element) every time the button is clicked.
Step 1: Create a helper method for date formatting
This method will generate your desired "yyyy-MM-dd HH:mm:ss" string whenever you need it:
private String getCurrentDateTime() { // For Java 7 and older SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); return dateFormat.format(new Date()); // If you're using Java 8+ (recommended for thread safety), use this instead: // DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // return LocalDateTime.now().format(formatter); }
Step 2: Trigger update on button click
In your button's click listener, call the helper method and update your string (or UI):
// Example: If you're displaying the date in a TextView TextView dateDisplay = findViewById(R.id.date_display_text); btn_send_msg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String currentDateTime = getCurrentDateTime(); // Update your string variable (if needed) // yourStringVariable = currentDateTime; // Or update the UI directly dateDisplay.setText(currentDateTime); } });
2. Write Date/Time to Firebase Child Elements
Let's fix and complete your incomplete Firebase code. The core idea is to add the formatted date string to your data map before pushing it to Firebase.
Step 1: Ensure Firebase reference is set up
First, make sure you have your Firebase Database reference initialized (usually in your activity's onCreate):
FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference root = database.getReference("your_root_collection"); // Replace with your actual root node name String temp_key;
Step 2: Complete the click listener for Firebase
Update your button's click logic to include the date/time in the data sent to Firebase:
btn_send_msg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Get the formatted date/time string String currentDateTime = getCurrentDateTime(); // Create a map to hold your message data (add other fields as needed) Map<String, Object> messageData = new HashMap<>(); messageData.put("timestamp", currentDateTime); // Add other fields like message content, sender info, etc. // messageData.put("message", yourMessageEditText.getText().toString()); // Generate a unique key for the new child element temp_key = root.push().getKey(); // Write the data to Firebase root.child(temp_key).setValue(messageData) .addOnSuccessListener(unused -> { // Optional: Show success feedback Toast.makeText(getApplicationContext(), "Data saved!", Toast.LENGTH_SHORT).show(); }) .addOnFailureListener(e -> { // Optional: Handle errors Toast.makeText(getApplicationContext(), "Failed to save data: " + e.getMessage(), Toast.LENGTH_SHORT).show(); }); } });
Quick Note: Firebase Server Timestamp
If you want more accurate timestamps (avoiding device time discrepancies), you can use Firebase's built-in server timestamp instead of formatting a local date:
// Replace the timestamp line with this messageData.put("timestamp", ServerValue.TIMESTAMP);
This stores the timestamp as a long (milliseconds since epoch), which you can format into your desired string when retrieving the data later.
内容的提问来源于stack exchange,提问作者Hrithik Rawal

